hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
588 values
lang
stringclasses
305 values
max_stars_repo_path
stringlengths
3
363
max_stars_repo_name
stringlengths
5
118
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
10
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringdate
2015-01-01 00:00:35
2022-03-31 23:43:49
max_stars_repo_stars_event_max_datetime
stringdate
2015-01-01 12:37:38
2022-03-31 23:59:52
max_issues_repo_path
stringlengths
3
363
max_issues_repo_name
stringlengths
5
118
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
10
max_issues_count
float64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
363
max_forks_repo_name
stringlengths
5
135
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
10
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringdate
2015-01-01 00:01:02
2022-03-31 23:27:27
max_forks_repo_forks_event_max_datetime
stringdate
2015-01-03 08:55:07
2022-03-31 23:59:24
content
stringlengths
5
1.05M
avg_line_length
float64
1.13
1.04M
max_line_length
int64
1
1.05M
alphanum_fraction
float64
0
1
13e326dda9c8d71db602450b61b690a93bd3ab82
1,548
h
C
mad_mp3dec.h
madmachineio/MadMP3Decoder
c9584dd0e8015f2db5a749cc9cdd9d2f86042ec9
[ "MIT" ]
null
null
null
mad_mp3dec.h
madmachineio/MadMP3Decoder
c9584dd0e8015f2db5a749cc9cdd9d2f86042ec9
[ "MIT" ]
null
null
null
mad_mp3dec.h
madmachineio/MadMP3Decoder
c9584dd0e8015f2db5a749cc9cdd9d2f86042ec9
[ "MIT" ]
null
null
null
/* * @Copyright (c) 2020, MADMACHINE LIMITED * @Author: Frank Li(lgl88911@163.com) * @SPDX-License-Identifier: MIT */ /** * @brief MP3 decoder PCM info * * @param channels decoder data channel number * @param sample_bits decoder frame data sample bits * @param sample_rate decoder data sample rate */ struct mad_mp3dec_pcm_info { int channels; int sample_bits; int sample_rate; }; typedef struct mad_mp3dec_pcm_info mad_mp3dec_pcm_info_t; /** * @brief Initialize the MP3 decoder * * @retval 0 If successful. * @retval Negative errno code if failure. */ int mad_mp3dec_init(void); /** * @brief Feed MP3 data to decode * * @param buf buffer of MP3 data * @param len feed size in byte * * @retval 0 If successful. * @retval Negative errno code if failure. */ int mad_mp3dec_feeddata(char *buf, int len); /** * @brief Decode MP3 data to output pcm data and pcm data info * * The remaining undecoded data will be feed first next call mad_mp3dec_feeddata * * @param buf Buffer of output pcm data * @param len Output data size of pcm in byte * @param pcm_info Output pcm data info * @param tail Output the remaining data without decoding * @param tail_len Un-decoding data size in byte * * @retval 0 If successful. * @retval Negative errno code if failure. */ int mad_mp3dec_decode(char *buf, int *len, mad_mp3dec_pcm_info_t *pcm_info, char *tail, int *tail_len); /** * @brief De-Init MP3 decoder * * @retval 0 If successful. * @retval Negative errno code if failure. */ int mad_mp3dec_deinit(void);
22.434783
103
0.717054
282fe79303ae7f2932ee81fc7c7ddef9de49996f
1,335
h
C
cpp/src/common/error.h
yxm1536/arctern
ef88ffd23bd91cb4fa9c5e8524a5e6ab53008117
[ "Apache-2.0" ]
68
2020-03-02T03:09:10.000Z
2020-05-27T06:26:55.000Z
cpp/src/common/error.h
yxm1536/arctern
ef88ffd23bd91cb4fa9c5e8524a5e6ab53008117
[ "Apache-2.0" ]
382
2020-02-29T07:48:52.000Z
2020-06-01T02:43:17.000Z
cpp/src/common/error.h
yxm1536/arctern
ef88ffd23bd91cb4fa9c5e8524a5e6ab53008117
[ "Apache-2.0" ]
47
2020-03-02T09:01:37.000Z
2020-06-01T03:07:27.000Z
/* * Copyright (C) 2019-2020 Zilliz. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once namespace arctern { using ErrorCode = unsigned int; constexpr ErrorCode ILLEGAL_VEGA_FORMAT = 5001; constexpr ErrorCode NULL_RENDER_OUTPUT = 5002; constexpr ErrorCode VALUE_TYPE_NOT_FOUND = 5003; constexpr ErrorCode INVALID_VEGA_DATA = 5004; constexpr ErrorCode UNKNOW_GEOMETYR_TYPE = 5005; constexpr ErrorCode FAILED_COMPILE_SHADER = 5006; constexpr ErrorCode FAILED_LINK_SHADER = 5007; constexpr ErrorCode COLOR_STYLE_NOT_FOUND = 5008; constexpr ErrorCode INVAILD_COLOR_FORMAT = 5009; constexpr ErrorCode LABEL_NOT_FOUND = 5010; constexpr ErrorCode FAILED_INIT_OSMESA = 5011; constexpr ErrorCode ILLEGAL_WKT_FORMAT = 6001; constexpr ErrorCode ILLEGAL_WKB_FORMAT = 6002; } // namespace arctern
35.131579
75
0.788764
9e13da6388585deaf6f892b941e0fe70b0b3a316
607
c
C
gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/i386/pr64317.c
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
7
2020-05-02T17:34:05.000Z
2021-10-17T10:15:18.000Z
gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/i386/pr64317.c
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
null
null
null
gcc-gcc-7_3_0-release/gcc/testsuite/gcc.target/i386/pr64317.c
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
2
2020-07-27T00:22:36.000Z
2021-04-01T09:41:02.000Z
/* { dg-do compile } */ /* { dg-require-effective-target ia32 } */ /* { dg-require-effective-target pie } */ /* { dg-options "-O2 -fpie" } */ /* { dg-final { scan-assembler "addl\[ \\t\]+\[$\]_GLOBAL_OFFSET_TABLE_, %ebx" } } */ /* { dg-final { scan-assembler "movl\[ \\t\]+c@GOTOFF\[(\]%ebx\[)\]" } } */ /* { dg-final { scan-assembler-not "movl\[ \\t\]+\[0-9]+\[(\]%esp\[)\], %ebx" } } */ long c = 1; int bar(); int foo (unsigned int iters) { unsigned int i; int res = 0; static long t1; for (i = 0; i < iters; i++) { res = bar(); t1 = c + res; } return t1 + res; }
22.481481
85
0.495881
9e2b9f6de7a82093a2da15c0636fa0e10cbec7ee
181,132
c
C
sys/fs/udf/udf_subr.c
calmsacibis995/minix
dfba95598f553b6560131d35a76658f1f8c9cf38
[ "Unlicense" ]
null
null
null
sys/fs/udf/udf_subr.c
calmsacibis995/minix
dfba95598f553b6560131d35a76658f1f8c9cf38
[ "Unlicense" ]
null
null
null
sys/fs/udf/udf_subr.c
calmsacibis995/minix
dfba95598f553b6560131d35a76658f1f8c9cf38
[ "Unlicense" ]
null
null
null
/* $NetBSD: udf_subr.c,v 1.132 2015/08/24 08:31:56 hannken Exp $ */ /* * Copyright (c) 2006, 2008 Reinoud Zandijk * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <sys/cdefs.h> #ifndef lint __KERNEL_RCSID(0, "$NetBSD: udf_subr.c,v 1.132 2015/08/24 08:31:56 hannken Exp $"); #endif /* not lint */ #if defined(_KERNEL_OPT) #include "opt_compat_netbsd.h" #endif #include <sys/param.h> #include <sys/systm.h> #include <sys/sysctl.h> #include <sys/namei.h> #include <sys/proc.h> #include <sys/kernel.h> #include <sys/vnode.h> #include <miscfs/genfs/genfs_node.h> #include <sys/mount.h> #include <sys/buf.h> #include <sys/file.h> #include <sys/device.h> #include <sys/disklabel.h> #include <sys/ioctl.h> #include <sys/malloc.h> #include <sys/dirent.h> #include <sys/stat.h> #include <sys/conf.h> #include <sys/kauth.h> #include <fs/unicode.h> #include <dev/clock_subr.h> #include <fs/udf/ecma167-udf.h> #include <fs/udf/udf_mount.h> #include <sys/dirhash.h> #include "udf.h" #include "udf_subr.h" #include "udf_bswap.h" #define VTOI(vnode) ((struct udf_node *) (vnode)->v_data) #define UDF_SET_SYSTEMFILE(vp) \ /* XXXAD Is the vnode locked? */ \ (vp)->v_vflag |= VV_SYSTEM; \ vref((vp)); \ vput((vp)); \ extern int syncer_maxdelay; /* maximum delay time */ extern int (**udf_vnodeop_p)(void *); /* --------------------------------------------------------------------- */ //#ifdef DEBUG #if 1 #if 0 static void udf_dumpblob(boid *blob, uint32_t dlen) { int i, j; printf("blob = %p\n", blob); printf("dump of %d bytes\n", dlen); for (i = 0; i < dlen; i+ = 16) { printf("%04x ", i); for (j = 0; j < 16; j++) { if (i+j < dlen) { printf("%02x ", blob[i+j]); } else { printf(" "); } } for (j = 0; j < 16; j++) { if (i+j < dlen) { if (blob[i+j]>32 && blob[i+j]! = 127) { printf("%c", blob[i+j]); } else { printf("."); } } } printf("\n"); } printf("\n"); Debugger(); } #endif static void udf_dump_discinfo(struct udf_mount *ump) { char bits[128]; struct mmc_discinfo *di = &ump->discinfo; if ((udf_verbose & UDF_DEBUG_VOLUMES) == 0) return; printf("Device/media info :\n"); printf("\tMMC profile 0x%02x\n", di->mmc_profile); printf("\tderived class %d\n", di->mmc_class); printf("\tsector size %d\n", di->sector_size); printf("\tdisc state %d\n", di->disc_state); printf("\tlast ses state %d\n", di->last_session_state); printf("\tbg format state %d\n", di->bg_format_state); printf("\tfrst track %d\n", di->first_track); printf("\tfst on last ses %d\n", di->first_track_last_session); printf("\tlst on last ses %d\n", di->last_track_last_session); printf("\tlink block penalty %d\n", di->link_block_penalty); snprintb(bits, sizeof(bits), MMC_DFLAGS_FLAGBITS, di->disc_flags); printf("\tdisc flags %s\n", bits); printf("\tdisc id %x\n", di->disc_id); printf("\tdisc barcode %"PRIx64"\n", di->disc_barcode); printf("\tnum sessions %d\n", di->num_sessions); printf("\tnum tracks %d\n", di->num_tracks); snprintb(bits, sizeof(bits), MMC_CAP_FLAGBITS, di->mmc_cur); printf("\tcapabilities cur %s\n", bits); snprintb(bits, sizeof(bits), MMC_CAP_FLAGBITS, di->mmc_cap); printf("\tcapabilities cap %s\n", bits); } static void udf_dump_trackinfo(struct mmc_trackinfo *trackinfo) { char bits[128]; if ((udf_verbose & UDF_DEBUG_VOLUMES) == 0) return; printf("Trackinfo for track %d:\n", trackinfo->tracknr); printf("\tsessionnr %d\n", trackinfo->sessionnr); printf("\ttrack mode %d\n", trackinfo->track_mode); printf("\tdata mode %d\n", trackinfo->data_mode); snprintb(bits, sizeof(bits), MMC_TRACKINFO_FLAGBITS, trackinfo->flags); printf("\tflags %s\n", bits); printf("\ttrack start %d\n", trackinfo->track_start); printf("\tnext_writable %d\n", trackinfo->next_writable); printf("\tfree_blocks %d\n", trackinfo->free_blocks); printf("\tpacket_size %d\n", trackinfo->packet_size); printf("\ttrack size %d\n", trackinfo->track_size); printf("\tlast recorded block %d\n", trackinfo->last_recorded); } #else #define udf_dump_discinfo(a); #define udf_dump_trackinfo(a); #endif /* --------------------------------------------------------------------- */ /* not called often */ int udf_update_discinfo(struct udf_mount *ump) { struct vnode *devvp = ump->devvp; uint64_t psize; unsigned secsize; struct mmc_discinfo *di; int error; DPRINTF(VOLUMES, ("read/update disc info\n")); di = &ump->discinfo; memset(di, 0, sizeof(struct mmc_discinfo)); /* check if we're on a MMC capable device, i.e. CD/DVD */ error = VOP_IOCTL(devvp, MMCGETDISCINFO, di, FKIOCTL, NOCRED); if (error == 0) { udf_dump_discinfo(ump); return 0; } /* disc partition support */ error = getdisksize(devvp, &psize, &secsize); if (error) return error; /* set up a disc info profile for partitions */ di->mmc_profile = 0x01; /* disc type */ di->mmc_class = MMC_CLASS_DISC; di->disc_state = MMC_STATE_CLOSED; di->last_session_state = MMC_STATE_CLOSED; di->bg_format_state = MMC_BGFSTATE_COMPLETED; di->link_block_penalty = 0; di->mmc_cur = MMC_CAP_RECORDABLE | MMC_CAP_REWRITABLE | MMC_CAP_ZEROLINKBLK | MMC_CAP_HW_DEFECTFREE; di->mmc_cap = di->mmc_cur; di->disc_flags = MMC_DFLAGS_UNRESTRICTED; /* TODO problem with last_possible_lba on resizable VND; request */ di->last_possible_lba = psize; di->sector_size = secsize; di->num_sessions = 1; di->num_tracks = 1; di->first_track = 1; di->first_track_last_session = di->last_track_last_session = 1; udf_dump_discinfo(ump); return 0; } int udf_update_trackinfo(struct udf_mount *ump, struct mmc_trackinfo *ti) { struct vnode *devvp = ump->devvp; struct mmc_discinfo *di = &ump->discinfo; int error, class; DPRINTF(VOLUMES, ("read track info\n")); class = di->mmc_class; if (class != MMC_CLASS_DISC) { /* tracknr specified in struct ti */ error = VOP_IOCTL(devvp, MMCGETTRACKINFO, ti, FKIOCTL, NOCRED); return error; } /* disc partition support */ if (ti->tracknr != 1) return EIO; /* create fake ti (TODO check for resized vnds) */ ti->sessionnr = 1; ti->track_mode = 0; /* XXX */ ti->data_mode = 0; /* XXX */ ti->flags = MMC_TRACKINFO_LRA_VALID | MMC_TRACKINFO_NWA_VALID; ti->track_start = 0; ti->packet_size = 1; /* TODO support for resizable vnd */ ti->track_size = di->last_possible_lba; ti->next_writable = di->last_possible_lba; ti->last_recorded = ti->next_writable; ti->free_blocks = 0; return 0; } int udf_setup_writeparams(struct udf_mount *ump) { struct mmc_writeparams mmc_writeparams; int error; if (ump->discinfo.mmc_class == MMC_CLASS_DISC) return 0; /* * only CD burning normally needs setting up, but other disc types * might need other settings to be made. The MMC framework will set up * the nessisary recording parameters according to the disc * characteristics read in. Modifications can be made in the discinfo * structure passed to change the nature of the disc. */ memset(&mmc_writeparams, 0, sizeof(struct mmc_writeparams)); mmc_writeparams.mmc_class = ump->discinfo.mmc_class; mmc_writeparams.mmc_cur = ump->discinfo.mmc_cur; /* * UDF dictates first track to determine track mode for the whole * disc. [UDF 1.50/6.10.1.1, UDF 1.50/6.10.2.1] * To prevent problems with a `reserved' track in front we start with * the 2nd track and if that is not valid, go for the 1st. */ mmc_writeparams.tracknr = 2; mmc_writeparams.data_mode = MMC_DATAMODE_DEFAULT; /* XA disc */ mmc_writeparams.track_mode = MMC_TRACKMODE_DEFAULT; /* data */ error = VOP_IOCTL(ump->devvp, MMCSETUPWRITEPARAMS, &mmc_writeparams, FKIOCTL, NOCRED); if (error) { mmc_writeparams.tracknr = 1; error = VOP_IOCTL(ump->devvp, MMCSETUPWRITEPARAMS, &mmc_writeparams, FKIOCTL, NOCRED); } return error; } int udf_synchronise_caches(struct udf_mount *ump) { struct mmc_op mmc_op; DPRINTF(CALL, ("udf_synchronise_caches()\n")); if (ump->vfs_mountp->mnt_flag & MNT_RDONLY) return 0; /* discs are done now */ if (ump->discinfo.mmc_class == MMC_CLASS_DISC) return 0; memset(&mmc_op, 0, sizeof(struct mmc_op)); mmc_op.operation = MMC_OP_SYNCHRONISECACHE; /* ignore return code */ (void) VOP_IOCTL(ump->devvp, MMCOP, &mmc_op, FKIOCTL, NOCRED); return 0; } /* --------------------------------------------------------------------- */ /* track/session searching for mounting */ int udf_search_tracks(struct udf_mount *ump, struct udf_args *args, int *first_tracknr, int *last_tracknr) { struct mmc_trackinfo trackinfo; uint32_t tracknr, start_track, num_tracks; int error; /* if negative, sessionnr is relative to last session */ if (args->sessionnr < 0) { args->sessionnr += ump->discinfo.num_sessions; } /* sanity */ if (args->sessionnr < 0) args->sessionnr = 0; if (args->sessionnr > ump->discinfo.num_sessions) args->sessionnr = ump->discinfo.num_sessions; /* search the tracks for this session, zero session nr indicates last */ if (args->sessionnr == 0) args->sessionnr = ump->discinfo.num_sessions; if (ump->discinfo.last_session_state == MMC_STATE_EMPTY) args->sessionnr--; /* sanity again */ if (args->sessionnr < 0) args->sessionnr = 0; /* search the first and last track of the specified session */ num_tracks = ump->discinfo.num_tracks; start_track = ump->discinfo.first_track; /* search for first track of this session */ for (tracknr = start_track; tracknr <= num_tracks; tracknr++) { /* get track info */ trackinfo.tracknr = tracknr; error = udf_update_trackinfo(ump, &trackinfo); if (error) return error; if (trackinfo.sessionnr == args->sessionnr) break; } *first_tracknr = tracknr; /* search for last track of this session */ for (;tracknr <= num_tracks; tracknr++) { /* get track info */ trackinfo.tracknr = tracknr; error = udf_update_trackinfo(ump, &trackinfo); if (error || (trackinfo.sessionnr != args->sessionnr)) { tracknr--; break; } } if (tracknr > num_tracks) tracknr--; *last_tracknr = tracknr; if (*last_tracknr < *first_tracknr) { printf( "udf_search_tracks: sanity check on drive+disc failed, " "drive returned garbage\n"); return EINVAL; } assert(*last_tracknr >= *first_tracknr); return 0; } /* * NOTE: this is the only routine in this file that directly peeks into the * metadata file but since its at a larval state of the mount it can't hurt. * * XXX candidate for udf_allocation.c * XXX clean me up!, change to new node reading code. */ static void udf_check_track_metadata_overlap(struct udf_mount *ump, struct mmc_trackinfo *trackinfo) { struct part_desc *part; struct file_entry *fe; struct extfile_entry *efe; struct short_ad *s_ad; struct long_ad *l_ad; uint32_t track_start, track_end; uint32_t phys_part_start, phys_part_end, part_start, part_end; uint32_t sector_size, len, alloclen, plb_num; uint8_t *pos; int addr_type, icblen, icbflags; /* get our track extents */ track_start = trackinfo->track_start; track_end = track_start + trackinfo->track_size; /* get our base partition extent */ KASSERT(ump->node_part == ump->fids_part); part = ump->partitions[ump->vtop[ump->node_part]]; phys_part_start = udf_rw32(part->start_loc); phys_part_end = phys_part_start + udf_rw32(part->part_len); /* no use if its outside the physical partition */ if ((phys_part_start >= track_end) || (phys_part_end < track_start)) return; /* * now follow all extents in the fe/efe to see if they refer to this * track */ sector_size = ump->discinfo.sector_size; /* XXX should we claim exclusive access to the metafile ? */ /* TODO: move to new node read code */ fe = ump->metadata_node->fe; efe = ump->metadata_node->efe; if (fe) { alloclen = udf_rw32(fe->l_ad); pos = &fe->data[0] + udf_rw32(fe->l_ea); icbflags = udf_rw16(fe->icbtag.flags); } else { assert(efe); alloclen = udf_rw32(efe->l_ad); pos = &efe->data[0] + udf_rw32(efe->l_ea); icbflags = udf_rw16(efe->icbtag.flags); } addr_type = icbflags & UDF_ICB_TAG_FLAGS_ALLOC_MASK; while (alloclen) { if (addr_type == UDF_ICB_SHORT_ALLOC) { icblen = sizeof(struct short_ad); s_ad = (struct short_ad *) pos; len = udf_rw32(s_ad->len); plb_num = udf_rw32(s_ad->lb_num); } else { /* should not be present, but why not */ icblen = sizeof(struct long_ad); l_ad = (struct long_ad *) pos; len = udf_rw32(l_ad->len); plb_num = udf_rw32(l_ad->loc.lb_num); /* pvpart_num = udf_rw16(l_ad->loc.part_num); */ } /* process extent */ len = UDF_EXT_LEN(len); part_start = phys_part_start + plb_num; part_end = part_start + (len / sector_size); if ((part_start >= track_start) && (part_end <= track_end)) { /* extent is enclosed within this track */ ump->metadata_track = *trackinfo; return; } pos += icblen; alloclen -= icblen; } } int udf_search_writing_tracks(struct udf_mount *ump) { struct vnode *devvp = ump->devvp; struct mmc_trackinfo trackinfo; struct mmc_op mmc_op; struct part_desc *part; uint32_t tracknr, start_track, num_tracks; uint32_t track_start, track_end, part_start, part_end; int node_alloc, error; /* * in the CD/(HD)DVD/BD recordable device model a few tracks within * the last session might be open but in the UDF device model at most * three tracks can be open: a reserved track for delayed ISO VRS * writing, a data track and a metadata track. We search here for the * data track and the metadata track. Note that the reserved track is * troublesome but can be detected by its small size of < 512 sectors. */ /* update discinfo since it might have changed */ error = udf_update_discinfo(ump); if (error) return error; num_tracks = ump->discinfo.num_tracks; start_track = ump->discinfo.first_track; /* fetch info on first and possibly only track */ trackinfo.tracknr = start_track; error = udf_update_trackinfo(ump, &trackinfo); if (error) return error; /* copy results to our mount point */ ump->data_track = trackinfo; ump->metadata_track = trackinfo; /* if not sequential, we're done */ if (num_tracks == 1) return 0; for (tracknr = start_track;tracknr <= num_tracks; tracknr++) { /* get track info */ trackinfo.tracknr = tracknr; error = udf_update_trackinfo(ump, &trackinfo); if (error) return error; /* * If this track is marked damaged, ask for repair. This is an * optional command, so ignore its error but report warning. */ if (trackinfo.flags & MMC_TRACKINFO_DAMAGED) { memset(&mmc_op, 0, sizeof(mmc_op)); mmc_op.operation = MMC_OP_REPAIRTRACK; mmc_op.mmc_profile = ump->discinfo.mmc_profile; mmc_op.tracknr = tracknr; error = VOP_IOCTL(devvp, MMCOP, &mmc_op, FKIOCTL, NOCRED); if (error) (void)printf("Drive can't explicitly repair " "damaged track %d, but it might " "autorepair\n", tracknr); /* reget track info */ error = udf_update_trackinfo(ump, &trackinfo); if (error) return error; } if ((trackinfo.flags & MMC_TRACKINFO_NWA_VALID) == 0) continue; track_start = trackinfo.track_start; track_end = track_start + trackinfo.track_size; /* check for overlap on data partition */ part = ump->partitions[ump->data_part]; part_start = udf_rw32(part->start_loc); part_end = part_start + udf_rw32(part->part_len); if ((part_start < track_end) && (part_end > track_start)) { ump->data_track = trackinfo; /* TODO check if UDF partition data_part is writable */ } /* check for overlap on metadata partition */ node_alloc = ump->vtop_alloc[ump->node_part]; if ((node_alloc == UDF_ALLOC_METASEQUENTIAL) || (node_alloc == UDF_ALLOC_METABITMAP)) { udf_check_track_metadata_overlap(ump, &trackinfo); } else { ump->metadata_track = trackinfo; } } if ((ump->data_track.flags & MMC_TRACKINFO_NWA_VALID) == 0) return EROFS; if ((ump->metadata_track.flags & MMC_TRACKINFO_NWA_VALID) == 0) return EROFS; return 0; } /* --------------------------------------------------------------------- */ /* * Check if the blob starts with a good UDF tag. Tags are protected by a * checksum over the reader except one byte at position 4 that is the checksum * itself. */ int udf_check_tag(void *blob) { struct desc_tag *tag = blob; uint8_t *pos, sum, cnt; /* check TAG header checksum */ pos = (uint8_t *) tag; sum = 0; for(cnt = 0; cnt < 16; cnt++) { if (cnt != 4) sum += *pos; pos++; } if (sum != tag->cksum) { /* bad tag header checksum; this is not a valid tag */ return EINVAL; } return 0; } /* * check tag payload will check descriptor CRC as specified. * If the descriptor is too long, it will return EIO otherwise EINVAL. */ int udf_check_tag_payload(void *blob, uint32_t max_length) { struct desc_tag *tag = blob; uint16_t crc, crc_len; crc_len = udf_rw16(tag->desc_crc_len); /* check payload CRC if applicable */ if (crc_len == 0) return 0; if (crc_len > max_length) return EIO; crc = udf_cksum(((uint8_t *) tag) + UDF_DESC_TAG_LENGTH, crc_len); if (crc != udf_rw16(tag->desc_crc)) { /* bad payload CRC; this is a broken tag */ return EINVAL; } return 0; } void udf_validate_tag_sum(void *blob) { struct desc_tag *tag = blob; uint8_t *pos, sum, cnt; /* calculate TAG header checksum */ pos = (uint8_t *) tag; sum = 0; for(cnt = 0; cnt < 16; cnt++) { if (cnt != 4) sum += *pos; pos++; } tag->cksum = sum; /* 8 bit */ } /* assumes sector number of descriptor to be saved already present */ void udf_validate_tag_and_crc_sums(void *blob) { struct desc_tag *tag = blob; uint8_t *btag = (uint8_t *) tag; uint16_t crc, crc_len; crc_len = udf_rw16(tag->desc_crc_len); /* check payload CRC if applicable */ if (crc_len > 0) { crc = udf_cksum(btag + UDF_DESC_TAG_LENGTH, crc_len); tag->desc_crc = udf_rw16(crc); } /* calculate TAG header checksum */ udf_validate_tag_sum(blob); } /* --------------------------------------------------------------------- */ /* * XXX note the different semantics from udfclient: for FIDs it still rounds * up to sectors. Use udf_fidsize() for a correct length. */ int udf_tagsize(union dscrptr *dscr, uint32_t lb_size) { uint32_t size, tag_id, num_lb, elmsz; tag_id = udf_rw16(dscr->tag.id); switch (tag_id) { case TAGID_LOGVOL : size = sizeof(struct logvol_desc) - 1; size += udf_rw32(dscr->lvd.mt_l); break; case TAGID_UNALLOC_SPACE : elmsz = sizeof(struct extent_ad); size = sizeof(struct unalloc_sp_desc) - elmsz; size += udf_rw32(dscr->usd.alloc_desc_num) * elmsz; break; case TAGID_FID : size = UDF_FID_SIZE + dscr->fid.l_fi + udf_rw16(dscr->fid.l_iu); size = (size + 3) & ~3; break; case TAGID_LOGVOL_INTEGRITY : size = sizeof(struct logvol_int_desc) - sizeof(uint32_t); size += udf_rw32(dscr->lvid.l_iu); size += (2 * udf_rw32(dscr->lvid.num_part) * sizeof(uint32_t)); break; case TAGID_SPACE_BITMAP : size = sizeof(struct space_bitmap_desc) - 1; size += udf_rw32(dscr->sbd.num_bytes); break; case TAGID_SPARING_TABLE : elmsz = sizeof(struct spare_map_entry); size = sizeof(struct udf_sparing_table) - elmsz; size += udf_rw16(dscr->spt.rt_l) * elmsz; break; case TAGID_FENTRY : size = sizeof(struct file_entry); size += udf_rw32(dscr->fe.l_ea) + udf_rw32(dscr->fe.l_ad)-1; break; case TAGID_EXTFENTRY : size = sizeof(struct extfile_entry); size += udf_rw32(dscr->efe.l_ea) + udf_rw32(dscr->efe.l_ad)-1; break; case TAGID_FSD : size = sizeof(struct fileset_desc); break; default : size = sizeof(union dscrptr); break; } if ((size == 0) || (lb_size == 0)) return 0; if (lb_size == 1) return size; /* round up in sectors */ num_lb = (size + lb_size -1) / lb_size; return num_lb * lb_size; } int udf_fidsize(struct fileid_desc *fid) { uint32_t size; if (udf_rw16(fid->tag.id) != TAGID_FID) panic("got udf_fidsize on non FID\n"); size = UDF_FID_SIZE + fid->l_fi + udf_rw16(fid->l_iu); size = (size + 3) & ~3; return size; } /* --------------------------------------------------------------------- */ void udf_lock_node(struct udf_node *udf_node, int flag, char const *fname, const int lineno) { int ret; mutex_enter(&udf_node->node_mutex); /* wait until free */ while (udf_node->i_flags & IN_LOCKED) { ret = cv_timedwait(&udf_node->node_lock, &udf_node->node_mutex, hz/8); /* TODO check if we should return error; abort */ if (ret == EWOULDBLOCK) { DPRINTF(LOCKING, ( "udf_lock_node: udf_node %p would block " "wanted at %s:%d, previously locked at %s:%d\n", udf_node, fname, lineno, udf_node->lock_fname, udf_node->lock_lineno)); } } /* grab */ udf_node->i_flags |= IN_LOCKED | flag; /* debug */ udf_node->lock_fname = fname; udf_node->lock_lineno = lineno; mutex_exit(&udf_node->node_mutex); } void udf_unlock_node(struct udf_node *udf_node, int flag) { mutex_enter(&udf_node->node_mutex); udf_node->i_flags &= ~(IN_LOCKED | flag); cv_broadcast(&udf_node->node_lock); mutex_exit(&udf_node->node_mutex); } /* --------------------------------------------------------------------- */ static int udf_read_anchor(struct udf_mount *ump, uint32_t sector, struct anchor_vdp **dst) { int error; error = udf_read_phys_dscr(ump, sector, M_UDFVOLD, (union dscrptr **) dst); if (!error) { /* blank terminator blocks are not allowed here */ if (*dst == NULL) return ENOENT; if (udf_rw16((*dst)->tag.id) != TAGID_ANCHOR) { error = ENOENT; free(*dst, M_UDFVOLD); *dst = NULL; DPRINTF(VOLUMES, ("Not an anchor\n")); } } return error; } int udf_read_anchors(struct udf_mount *ump) { struct udf_args *args = &ump->mount_args; struct mmc_trackinfo first_track; struct mmc_trackinfo second_track; struct mmc_trackinfo last_track; struct anchor_vdp **anchorsp; uint32_t track_start; uint32_t track_end; uint32_t positions[4]; int first_tracknr, last_tracknr; int error, anch, ok, first_anchor; /* search the first and last track of the specified session */ error = udf_search_tracks(ump, args, &first_tracknr, &last_tracknr); if (!error) { first_track.tracknr = first_tracknr; error = udf_update_trackinfo(ump, &first_track); } if (!error) { last_track.tracknr = last_tracknr; error = udf_update_trackinfo(ump, &last_track); } if ((!error) && (first_tracknr != last_tracknr)) { second_track.tracknr = first_tracknr+1; error = udf_update_trackinfo(ump, &second_track); } if (error) { printf("UDF mount: reading disc geometry failed\n"); return 0; } track_start = first_track.track_start; /* `end' is not as straitforward as start. */ track_end = last_track.track_start + last_track.track_size - last_track.free_blocks - 1; if (ump->discinfo.mmc_cur & MMC_CAP_SEQUENTIAL) { /* end of track is not straitforward here */ if (last_track.flags & MMC_TRACKINFO_LRA_VALID) track_end = last_track.last_recorded; else if (last_track.flags & MMC_TRACKINFO_NWA_VALID) track_end = last_track.next_writable - ump->discinfo.link_block_penalty; } /* its no use reading a blank track */ first_anchor = 0; if (first_track.flags & MMC_TRACKINFO_BLANK) first_anchor = 1; /* get our packet size */ ump->packet_size = first_track.packet_size; if (first_track.flags & MMC_TRACKINFO_BLANK) ump->packet_size = second_track.packet_size; if (ump->packet_size <= 1) { /* take max, but not bigger than 64 */ ump->packet_size = MAXPHYS / ump->discinfo.sector_size; ump->packet_size = MIN(ump->packet_size, 64); } KASSERT(ump->packet_size >= 1); /* read anchors start+256, start+512, end-256, end */ positions[0] = track_start+256; positions[1] = track_end-256; positions[2] = track_end; positions[3] = track_start+512; /* [UDF 2.60/6.11.2] */ /* XXX shouldn't +512 be prefered above +256 for compat with Roxio CD */ ok = 0; anchorsp = ump->anchors; for (anch = first_anchor; anch < 4; anch++) { DPRINTF(VOLUMES, ("Read anchor %d at sector %d\n", anch, positions[anch])); error = udf_read_anchor(ump, positions[anch], anchorsp); if (!error) { anchorsp++; ok++; } } /* VATs are only recorded on sequential media, but initialise */ ump->first_possible_vat_location = track_start + 2; ump->last_possible_vat_location = track_end + last_track.packet_size; return ok; } /* --------------------------------------------------------------------- */ int udf_get_c_type(struct udf_node *udf_node) { int isdir, what; isdir = (udf_node->vnode->v_type == VDIR); what = isdir ? UDF_C_FIDS : UDF_C_USERDATA; if (udf_node->ump) if (udf_node == udf_node->ump->metadatabitmap_node) what = UDF_C_METADATA_SBM; return what; } int udf_get_record_vpart(struct udf_mount *ump, int udf_c_type) { int vpart_num; vpart_num = ump->data_part; if (udf_c_type == UDF_C_NODE) vpart_num = ump->node_part; if (udf_c_type == UDF_C_FIDS) vpart_num = ump->fids_part; return vpart_num; } /* * BUGALERT: some rogue implementations use random physical partition * numbers to break other implementations so lookup the number. */ static uint16_t udf_find_raw_phys(struct udf_mount *ump, uint16_t raw_phys_part) { struct part_desc *part; uint16_t phys_part; for (phys_part = 0; phys_part < UDF_PARTITIONS; phys_part++) { part = ump->partitions[phys_part]; if (part == NULL) break; if (udf_rw16(part->part_num) == raw_phys_part) break; } return phys_part; } /* --------------------------------------------------------------------- */ /* we dont try to be smart; we just record the parts */ #define UDF_UPDATE_DSCR(name, dscr) \ if (name) \ free(name, M_UDFVOLD); \ name = dscr; static int udf_process_vds_descriptor(struct udf_mount *ump, union dscrptr *dscr) { uint16_t phys_part, raw_phys_part; DPRINTF(VOLUMES, ("\tprocessing VDS descr %d\n", udf_rw16(dscr->tag.id))); switch (udf_rw16(dscr->tag.id)) { case TAGID_PRI_VOL : /* primary partition */ UDF_UPDATE_DSCR(ump->primary_vol, &dscr->pvd); break; case TAGID_LOGVOL : /* logical volume */ UDF_UPDATE_DSCR(ump->logical_vol, &dscr->lvd); break; case TAGID_UNALLOC_SPACE : /* unallocated space */ UDF_UPDATE_DSCR(ump->unallocated, &dscr->usd); break; case TAGID_IMP_VOL : /* implementation */ /* XXX do we care about multiple impl. descr ? */ UDF_UPDATE_DSCR(ump->implementation, &dscr->ivd); break; case TAGID_PARTITION : /* physical partition */ /* not much use if its not allocated */ if ((udf_rw16(dscr->pd.flags) & UDF_PART_FLAG_ALLOCATED) == 0) { free(dscr, M_UDFVOLD); break; } /* * BUGALERT: some rogue implementations use random physical * partition numbers to break other implementations so lookup * the number. */ raw_phys_part = udf_rw16(dscr->pd.part_num); phys_part = udf_find_raw_phys(ump, raw_phys_part); if (phys_part == UDF_PARTITIONS) { free(dscr, M_UDFVOLD); return EINVAL; } UDF_UPDATE_DSCR(ump->partitions[phys_part], &dscr->pd); break; case TAGID_VOL : /* volume space extender; rare */ DPRINTF(VOLUMES, ("VDS extender ignored\n")); free(dscr, M_UDFVOLD); break; default : DPRINTF(VOLUMES, ("Unhandled VDS type %d\n", udf_rw16(dscr->tag.id))); free(dscr, M_UDFVOLD); } return 0; } #undef UDF_UPDATE_DSCR /* --------------------------------------------------------------------- */ static int udf_read_vds_extent(struct udf_mount *ump, uint32_t loc, uint32_t len) { union dscrptr *dscr; uint32_t sector_size, dscr_size; int error; sector_size = ump->discinfo.sector_size; /* loc is sectornr, len is in bytes */ error = EIO; while (len) { error = udf_read_phys_dscr(ump, loc, M_UDFVOLD, &dscr); if (error) return error; /* blank block is a terminator */ if (dscr == NULL) return 0; /* TERM descriptor is a terminator */ if (udf_rw16(dscr->tag.id) == TAGID_TERM) { free(dscr, M_UDFVOLD); return 0; } /* process all others */ dscr_size = udf_tagsize(dscr, sector_size); error = udf_process_vds_descriptor(ump, dscr); if (error) { free(dscr, M_UDFVOLD); break; } assert((dscr_size % sector_size) == 0); len -= dscr_size; loc += dscr_size / sector_size; } return error; } int udf_read_vds_space(struct udf_mount *ump) { /* struct udf_args *args = &ump->mount_args; */ struct anchor_vdp *anchor, *anchor2; size_t size; uint32_t main_loc, main_len; uint32_t reserve_loc, reserve_len; int error; /* * read in VDS space provided by the anchors; if one descriptor read * fails, try the mirror sector. * * check if 2nd anchor is different from 1st; if so, go for 2nd. This * avoids the `compatibility features' of DirectCD that may confuse * stuff completely. */ anchor = ump->anchors[0]; anchor2 = ump->anchors[1]; assert(anchor); if (anchor2) { size = sizeof(struct extent_ad); if (memcmp(&anchor->main_vds_ex, &anchor2->main_vds_ex, size)) anchor = anchor2; /* reserve is specified to be a literal copy of main */ } main_loc = udf_rw32(anchor->main_vds_ex.loc); main_len = udf_rw32(anchor->main_vds_ex.len); reserve_loc = udf_rw32(anchor->reserve_vds_ex.loc); reserve_len = udf_rw32(anchor->reserve_vds_ex.len); error = udf_read_vds_extent(ump, main_loc, main_len); if (error) { printf("UDF mount: reading in reserve VDS extent\n"); error = udf_read_vds_extent(ump, reserve_loc, reserve_len); } return error; } /* --------------------------------------------------------------------- */ /* * Read in the logical volume integrity sequence pointed to by our logical * volume descriptor. Its a sequence that can be extended using fields in the * integrity descriptor itself. On sequential media only one is found, on * rewritable media a sequence of descriptors can be found as a form of * history keeping and on non sequential write-once media the chain is vital * to allow more and more descriptors to be written. The last descriptor * written in an extent needs to claim space for a new extent. */ static int udf_retrieve_lvint(struct udf_mount *ump) { union dscrptr *dscr; struct logvol_int_desc *lvint; struct udf_lvintq *trace; uint32_t lb_size, lbnum, len; int dscr_type, error, trace_len; lb_size = udf_rw32(ump->logical_vol->lb_size); len = udf_rw32(ump->logical_vol->integrity_seq_loc.len); lbnum = udf_rw32(ump->logical_vol->integrity_seq_loc.loc); /* clean trace */ memset(ump->lvint_trace, 0, UDF_LVDINT_SEGMENTS * sizeof(struct udf_lvintq)); trace_len = 0; trace = ump->lvint_trace; trace->start = lbnum; trace->end = lbnum + len/lb_size; trace->pos = 0; trace->wpos = 0; lvint = NULL; dscr = NULL; error = 0; while (len) { trace->pos = lbnum - trace->start; trace->wpos = trace->pos + 1; /* read in our integrity descriptor */ error = udf_read_phys_dscr(ump, lbnum, M_UDFVOLD, &dscr); if (!error) { if (dscr == NULL) { trace->wpos = trace->pos; break; /* empty terminates */ } dscr_type = udf_rw16(dscr->tag.id); if (dscr_type == TAGID_TERM) { trace->wpos = trace->pos; break; /* clean terminator */ } if (dscr_type != TAGID_LOGVOL_INTEGRITY) { /* fatal... corrupt disc */ error = ENOENT; break; } if (lvint) free(lvint, M_UDFVOLD); lvint = &dscr->lvid; dscr = NULL; } /* else hope for the best... maybe the next is ok */ DPRINTFIF(VOLUMES, lvint, ("logvol integrity read, state %s\n", udf_rw32(lvint->integrity_type) ? "CLOSED" : "OPEN")); /* proceed sequential */ lbnum += 1; len -= lb_size; /* are we linking to a new piece? */ if (dscr && lvint->next_extent.len) { len = udf_rw32(lvint->next_extent.len); lbnum = udf_rw32(lvint->next_extent.loc); if (trace_len >= UDF_LVDINT_SEGMENTS-1) { /* IEK! segment link full... */ DPRINTF(VOLUMES, ("lvdint segments full\n")); error = EINVAL; } else { trace++; trace_len++; trace->start = lbnum; trace->end = lbnum + len/lb_size; trace->pos = 0; trace->wpos = 0; } } } /* clean up the mess, esp. when there is an error */ if (dscr) free(dscr, M_UDFVOLD); if (error && lvint) { free(lvint, M_UDFVOLD); lvint = NULL; } if (!lvint) error = ENOENT; ump->logvol_integrity = lvint; return error; } static int udf_loose_lvint_history(struct udf_mount *ump) { union dscrptr **bufs, *dscr, *last_dscr; struct udf_lvintq *trace, *in_trace, *out_trace; struct logvol_int_desc *lvint; uint32_t in_ext, in_pos, in_len; uint32_t out_ext, out_wpos, out_len; uint32_t lb_num; uint32_t len, start; int ext, minext, extlen, cnt, cpy_len, dscr_type; int losing; int error; DPRINTF(VOLUMES, ("need to lose some lvint history\n")); /* search smallest extent */ trace = &ump->lvint_trace[0]; minext = trace->end - trace->start; for (ext = 1; ext < UDF_LVDINT_SEGMENTS; ext++) { trace = &ump->lvint_trace[ext]; extlen = trace->end - trace->start; if (extlen == 0) break; minext = MIN(minext, extlen); } losing = MIN(minext, UDF_LVINT_LOSSAGE); /* no sense wiping all */ if (losing == minext) losing--; DPRINTF(VOLUMES, ("\tlosing %d entries\n", losing)); /* get buffer for pieces */ bufs = malloc(UDF_LVDINT_SEGMENTS * sizeof(void *), M_TEMP, M_WAITOK); in_ext = 0; in_pos = losing; in_trace = &ump->lvint_trace[in_ext]; in_len = in_trace->end - in_trace->start; out_ext = 0; out_wpos = 0; out_trace = &ump->lvint_trace[out_ext]; out_len = out_trace->end - out_trace->start; last_dscr = NULL; for(;;) { out_trace->pos = out_wpos; out_trace->wpos = out_trace->pos; if (in_pos >= in_len) { in_ext++; in_pos = 0; in_trace = &ump->lvint_trace[in_ext]; in_len = in_trace->end - in_trace->start; } if (out_wpos >= out_len) { out_ext++; out_wpos = 0; out_trace = &ump->lvint_trace[out_ext]; out_len = out_trace->end - out_trace->start; } /* copy overlap contents */ cpy_len = MIN(in_len - in_pos, out_len - out_wpos); cpy_len = MIN(cpy_len, in_len - in_trace->pos); if (cpy_len == 0) break; /* copy */ DPRINTF(VOLUMES, ("\treading %d lvid descriptors\n", cpy_len)); for (cnt = 0; cnt < cpy_len; cnt++) { /* read in our integrity descriptor */ lb_num = in_trace->start + in_pos + cnt; error = udf_read_phys_dscr(ump, lb_num, M_UDFVOLD, &dscr); if (error) { /* copy last one */ dscr = last_dscr; } bufs[cnt] = dscr; if (!error) { if (dscr == NULL) { out_trace->pos = out_wpos + cnt; out_trace->wpos = out_trace->pos; break; /* empty terminates */ } dscr_type = udf_rw16(dscr->tag.id); if (dscr_type == TAGID_TERM) { out_trace->pos = out_wpos + cnt; out_trace->wpos = out_trace->pos; break; /* clean terminator */ } if (dscr_type != TAGID_LOGVOL_INTEGRITY) { panic( "UDF integrity sequence " "corrupted while mounted!\n"); } last_dscr = dscr; } } /* patch up if first entry was on error */ if (bufs[0] == NULL) { for (cnt = 0; cnt < cpy_len; cnt++) if (bufs[cnt] != NULL) break; last_dscr = bufs[cnt]; for (; cnt > 0; cnt--) { bufs[cnt] = last_dscr; } } /* glue + write out */ DPRINTF(VOLUMES, ("\twriting %d lvid descriptors\n", cpy_len)); for (cnt = 0; cnt < cpy_len; cnt++) { lb_num = out_trace->start + out_wpos + cnt; lvint = &bufs[cnt]->lvid; /* set continuation */ len = 0; start = 0; if (out_wpos + cnt == out_len) { /* get continuation */ trace = &ump->lvint_trace[out_ext+1]; len = trace->end - trace->start; start = trace->start; } lvint->next_extent.len = udf_rw32(len); lvint->next_extent.loc = udf_rw32(start); lb_num = trace->start + trace->wpos; error = udf_write_phys_dscr_sync(ump, NULL, UDF_C_DSCR, bufs[cnt], lb_num, lb_num); DPRINTFIF(VOLUMES, error, ("error writing lvint lb_num\n")); } /* free non repeating descriptors */ last_dscr = NULL; for (cnt = 0; cnt < cpy_len; cnt++) { if (bufs[cnt] != last_dscr) free(bufs[cnt], M_UDFVOLD); last_dscr = bufs[cnt]; } /* advance */ in_pos += cpy_len; out_wpos += cpy_len; } free(bufs, M_TEMP); return 0; } static int udf_writeout_lvint(struct udf_mount *ump, int lvflag) { struct udf_lvintq *trace; struct timeval now_v; struct timespec now_s; uint32_t sector; int logvol_integrity; int space, error; DPRINTF(VOLUMES, ("writing out logvol integrity descriptor\n")); again: /* get free space in last chunk */ trace = ump->lvint_trace; while (trace->wpos > (trace->end - trace->start)) { DPRINTF(VOLUMES, ("skip : start = %d, end = %d, pos = %d, " "wpos = %d\n", trace->start, trace->end, trace->pos, trace->wpos)); trace++; } /* check if there is space to append */ space = (trace->end - trace->start) - trace->wpos; DPRINTF(VOLUMES, ("write start = %d, end = %d, pos = %d, wpos = %d, " "space = %d\n", trace->start, trace->end, trace->pos, trace->wpos, space)); /* get state */ logvol_integrity = udf_rw32(ump->logvol_integrity->integrity_type); if (logvol_integrity == UDF_INTEGRITY_CLOSED) { if ((space < 3) && (lvflag & UDF_APPENDONLY_LVINT)) { /* TODO extent LVINT space if possible */ return EROFS; } } if (space < 1) { if (lvflag & UDF_APPENDONLY_LVINT) return EROFS; /* loose history by re-writing extents */ error = udf_loose_lvint_history(ump); if (error) return error; goto again; } /* update our integrity descriptor to identify us and timestamp it */ DPRINTF(VOLUMES, ("updating integrity descriptor\n")); microtime(&now_v); TIMEVAL_TO_TIMESPEC(&now_v, &now_s); udf_timespec_to_timestamp(&now_s, &ump->logvol_integrity->time); udf_set_regid(&ump->logvol_info->impl_id, IMPL_NAME); udf_add_impl_regid(ump, &ump->logvol_info->impl_id); /* writeout integrity descriptor */ sector = trace->start + trace->wpos; error = udf_write_phys_dscr_sync(ump, NULL, UDF_C_DSCR, (union dscrptr *) ump->logvol_integrity, sector, sector); DPRINTF(VOLUMES, ("writeout lvint : error = %d\n", error)); if (error) return error; /* advance write position */ trace->wpos++; space--; if (space >= 1) { /* append terminator */ sector = trace->start + trace->wpos; error = udf_write_terminator(ump, sector); DPRINTF(VOLUMES, ("write terminator : error = %d\n", error)); } space = (trace->end - trace->start) - trace->wpos; DPRINTF(VOLUMES, ("write start = %d, end = %d, pos = %d, wpos = %d, " "space = %d\n", trace->start, trace->end, trace->pos, trace->wpos, space)); DPRINTF(VOLUMES, ("finished writing out logvol integrity descriptor " "successfull\n")); return error; } /* --------------------------------------------------------------------- */ static int udf_read_physical_partition_spacetables(struct udf_mount *ump) { union dscrptr *dscr; /* struct udf_args *args = &ump->mount_args; */ struct part_desc *partd; struct part_hdr_desc *parthdr; struct udf_bitmap *bitmap; uint32_t phys_part; uint32_t lb_num, len; int error, dscr_type; /* unallocated space map */ for (phys_part = 0; phys_part < UDF_PARTITIONS; phys_part++) { partd = ump->partitions[phys_part]; if (partd == NULL) continue; parthdr = &partd->_impl_use.part_hdr; lb_num = udf_rw32(partd->start_loc); lb_num += udf_rw32(parthdr->unalloc_space_bitmap.lb_num); len = udf_rw32(parthdr->unalloc_space_bitmap.len); if (len == 0) continue; DPRINTF(VOLUMES, ("Read unalloc. space bitmap %d\n", lb_num)); error = udf_read_phys_dscr(ump, lb_num, M_UDFVOLD, &dscr); if (!error && dscr) { /* analyse */ dscr_type = udf_rw16(dscr->tag.id); if (dscr_type == TAGID_SPACE_BITMAP) { DPRINTF(VOLUMES, ("Accepting space bitmap\n")); ump->part_unalloc_dscr[phys_part] = &dscr->sbd; /* fill in ump->part_unalloc_bits */ bitmap = &ump->part_unalloc_bits[phys_part]; bitmap->blob = (uint8_t *) dscr; bitmap->bits = dscr->sbd.data; bitmap->max_offset = udf_rw32(dscr->sbd.num_bits); bitmap->pages = NULL; /* TODO */ bitmap->data_pos = 0; bitmap->metadata_pos = 0; } else { free(dscr, M_UDFVOLD); printf( "UDF mount: error reading unallocated " "space bitmap\n"); return EROFS; } } else { /* blank not allowed */ printf("UDF mount: blank unallocated space bitmap\n"); return EROFS; } } /* unallocated space table (not supported) */ for (phys_part = 0; phys_part < UDF_PARTITIONS; phys_part++) { partd = ump->partitions[phys_part]; if (partd == NULL) continue; parthdr = &partd->_impl_use.part_hdr; len = udf_rw32(parthdr->unalloc_space_table.len); if (len) { printf("UDF mount: space tables not supported\n"); return EROFS; } } /* freed space map */ for (phys_part = 0; phys_part < UDF_PARTITIONS; phys_part++) { partd = ump->partitions[phys_part]; if (partd == NULL) continue; parthdr = &partd->_impl_use.part_hdr; /* freed space map */ lb_num = udf_rw32(partd->start_loc); lb_num += udf_rw32(parthdr->freed_space_bitmap.lb_num); len = udf_rw32(parthdr->freed_space_bitmap.len); if (len == 0) continue; DPRINTF(VOLUMES, ("Read unalloc. space bitmap %d\n", lb_num)); error = udf_read_phys_dscr(ump, lb_num, M_UDFVOLD, &dscr); if (!error && dscr) { /* analyse */ dscr_type = udf_rw16(dscr->tag.id); if (dscr_type == TAGID_SPACE_BITMAP) { DPRINTF(VOLUMES, ("Accepting space bitmap\n")); ump->part_freed_dscr[phys_part] = &dscr->sbd; /* fill in ump->part_freed_bits */ bitmap = &ump->part_unalloc_bits[phys_part]; bitmap->blob = (uint8_t *) dscr; bitmap->bits = dscr->sbd.data; bitmap->max_offset = udf_rw32(dscr->sbd.num_bits); bitmap->pages = NULL; /* TODO */ bitmap->data_pos = 0; bitmap->metadata_pos = 0; } else { free(dscr, M_UDFVOLD); printf( "UDF mount: error reading freed " "space bitmap\n"); return EROFS; } } else { /* blank not allowed */ printf("UDF mount: blank freed space bitmap\n"); return EROFS; } } /* freed space table (not supported) */ for (phys_part = 0; phys_part < UDF_PARTITIONS; phys_part++) { partd = ump->partitions[phys_part]; if (partd == NULL) continue; parthdr = &partd->_impl_use.part_hdr; len = udf_rw32(parthdr->freed_space_table.len); if (len) { printf("UDF mount: space tables not supported\n"); return EROFS; } } return 0; } /* TODO implement async writeout */ int udf_write_physical_partition_spacetables(struct udf_mount *ump, int waitfor) { union dscrptr *dscr; /* struct udf_args *args = &ump->mount_args; */ struct part_desc *partd; struct part_hdr_desc *parthdr; uint32_t phys_part; uint32_t lb_num, len, ptov; int error_all, error; error_all = 0; /* unallocated space map */ for (phys_part = 0; phys_part < UDF_PARTITIONS; phys_part++) { partd = ump->partitions[phys_part]; if (partd == NULL) continue; parthdr = &partd->_impl_use.part_hdr; ptov = udf_rw32(partd->start_loc); lb_num = udf_rw32(parthdr->unalloc_space_bitmap.lb_num); len = udf_rw32(parthdr->unalloc_space_bitmap.len); if (len == 0) continue; DPRINTF(VOLUMES, ("Write unalloc. space bitmap %d\n", lb_num + ptov)); dscr = (union dscrptr *) ump->part_unalloc_dscr[phys_part]; error = udf_write_phys_dscr_sync(ump, NULL, UDF_C_DSCR, (union dscrptr *) dscr, ptov + lb_num, lb_num); if (error) { DPRINTF(VOLUMES, ("\tfailed!! (error %d)\n", error)); error_all = error; } } /* freed space map */ for (phys_part = 0; phys_part < UDF_PARTITIONS; phys_part++) { partd = ump->partitions[phys_part]; if (partd == NULL) continue; parthdr = &partd->_impl_use.part_hdr; /* freed space map */ ptov = udf_rw32(partd->start_loc); lb_num = udf_rw32(parthdr->freed_space_bitmap.lb_num); len = udf_rw32(parthdr->freed_space_bitmap.len); if (len == 0) continue; DPRINTF(VOLUMES, ("Write freed space bitmap %d\n", lb_num + ptov)); dscr = (union dscrptr *) ump->part_freed_dscr[phys_part]; error = udf_write_phys_dscr_sync(ump, NULL, UDF_C_DSCR, (union dscrptr *) dscr, ptov + lb_num, lb_num); if (error) { DPRINTF(VOLUMES, ("\tfailed!! (error %d)\n", error)); error_all = error; } } return error_all; } static int udf_read_metadata_partition_spacetable(struct udf_mount *ump) { struct udf_node *bitmap_node; union dscrptr *dscr; struct udf_bitmap *bitmap; uint64_t inflen; int error, dscr_type; bitmap_node = ump->metadatabitmap_node; /* only read in when metadata bitmap node is read in */ if (bitmap_node == NULL) return 0; if (bitmap_node->fe) { inflen = udf_rw64(bitmap_node->fe->inf_len); } else { KASSERT(bitmap_node->efe); inflen = udf_rw64(bitmap_node->efe->inf_len); } DPRINTF(VOLUMES, ("Reading metadata space bitmap for " "%"PRIu64" bytes\n", inflen)); /* allocate space for bitmap */ dscr = malloc(inflen, M_UDFVOLD, M_CANFAIL | M_WAITOK); if (!dscr) return ENOMEM; /* set vnode type to regular file or we can't read from it! */ bitmap_node->vnode->v_type = VREG; /* read in complete metadata bitmap file */ error = vn_rdwr(UIO_READ, bitmap_node->vnode, dscr, inflen, 0, UIO_SYSSPACE, IO_SYNC | IO_ALTSEMANTICS, FSCRED, NULL, NULL); if (error) { DPRINTF(VOLUMES, ("Error reading metadata space bitmap\n")); goto errorout; } /* analyse */ dscr_type = udf_rw16(dscr->tag.id); if (dscr_type == TAGID_SPACE_BITMAP) { DPRINTF(VOLUMES, ("Accepting metadata space bitmap\n")); ump->metadata_unalloc_dscr = &dscr->sbd; /* fill in bitmap bits */ bitmap = &ump->metadata_unalloc_bits; bitmap->blob = (uint8_t *) dscr; bitmap->bits = dscr->sbd.data; bitmap->max_offset = udf_rw32(dscr->sbd.num_bits); bitmap->pages = NULL; /* TODO */ bitmap->data_pos = 0; bitmap->metadata_pos = 0; } else { DPRINTF(VOLUMES, ("No valid bitmap found!\n")); goto errorout; } return 0; errorout: free(dscr, M_UDFVOLD); printf( "UDF mount: error reading unallocated " "space bitmap for metadata partition\n"); return EROFS; } int udf_write_metadata_partition_spacetable(struct udf_mount *ump, int waitfor) { struct udf_node *bitmap_node; union dscrptr *dscr; uint64_t new_inflen; int dummy, error; bitmap_node = ump->metadatabitmap_node; /* only write out when metadata bitmap node is known */ if (bitmap_node == NULL) return 0; if (!bitmap_node->fe) { KASSERT(bitmap_node->efe); } /* reduce length to zero */ dscr = (union dscrptr *) ump->metadata_unalloc_dscr; new_inflen = udf_tagsize(dscr, 1); DPRINTF(VOLUMES, ("Resize and write out metadata space bitmap " " for %"PRIu64" bytes\n", new_inflen)); error = udf_resize_node(bitmap_node, new_inflen, &dummy); if (error) printf("Error resizing metadata space bitmap\n"); error = vn_rdwr(UIO_WRITE, bitmap_node->vnode, dscr, new_inflen, 0, UIO_SYSSPACE, IO_ALTSEMANTICS, FSCRED, NULL, NULL); bitmap_node->i_flags |= IN_MODIFIED; error = vflushbuf(bitmap_node->vnode, FSYNC_WAIT); if (error == 0) error = VOP_FSYNC(bitmap_node->vnode, FSCRED, FSYNC_WAIT, 0, 0); if (error) printf( "Error writing out metadata partition unalloced " "space bitmap!\n"); return error; } /* --------------------------------------------------------------------- */ /* * Checks if ump's vds information is correct and complete */ int udf_process_vds(struct udf_mount *ump) { union udf_pmap *mapping; /* struct udf_args *args = &ump->mount_args; */ struct logvol_int_desc *lvint; struct udf_logvol_info *lvinfo; uint32_t n_pm; uint8_t *pmap_pos; char *domain_name, *map_name; const char *check_name; char bits[128]; int pmap_stype, pmap_size; int pmap_type, log_part, phys_part, raw_phys_part, maps_on; int n_phys, n_virt, n_spar, n_meta; int len; if (ump == NULL) return ENOENT; /* we need at least an anchor (trivial, but for safety) */ if (ump->anchors[0] == NULL) return EINVAL; /* we need at least one primary and one logical volume descriptor */ if ((ump->primary_vol == NULL) || (ump->logical_vol) == NULL) return EINVAL; /* we need at least one partition descriptor */ if (ump->partitions[0] == NULL) return EINVAL; /* check logical volume sector size verses device sector size */ if (udf_rw32(ump->logical_vol->lb_size) != ump->discinfo.sector_size) { printf("UDF mount: format violation, lb_size != sector size\n"); return EINVAL; } /* check domain name */ domain_name = ump->logical_vol->domain_id.id; if (strncmp(domain_name, "*OSTA UDF Compliant", 20)) { printf("mount_udf: disc not OSTA UDF Compliant, aborting\n"); return EINVAL; } /* retrieve logical volume integrity sequence */ (void)udf_retrieve_lvint(ump); /* * We need at least one logvol integrity descriptor recorded. Note * that its OK to have an open logical volume integrity here. The VAT * will close/update the integrity. */ if (ump->logvol_integrity == NULL) return EINVAL; /* process derived structures */ n_pm = udf_rw32(ump->logical_vol->n_pm); /* num partmaps */ lvint = ump->logvol_integrity; lvinfo = (struct udf_logvol_info *) (&lvint->tables[2 * n_pm]); ump->logvol_info = lvinfo; /* TODO check udf versions? */ /* * check logvol mappings: effective virt->log partmap translation * check and recording of the mapping results. Saves expensive * strncmp() in tight places. */ DPRINTF(VOLUMES, ("checking logvol mappings\n")); n_pm = udf_rw32(ump->logical_vol->n_pm); /* num partmaps */ pmap_pos = ump->logical_vol->maps; if (n_pm > UDF_PMAPS) { printf("UDF mount: too many mappings\n"); return EINVAL; } /* count types and set partition numbers */ ump->data_part = ump->node_part = ump->fids_part = 0; n_phys = n_virt = n_spar = n_meta = 0; for (log_part = 0; log_part < n_pm; log_part++) { mapping = (union udf_pmap *) pmap_pos; pmap_stype = pmap_pos[0]; pmap_size = pmap_pos[1]; switch (pmap_stype) { case 1: /* physical mapping */ /* volseq = udf_rw16(mapping->pm1.vol_seq_num); */ raw_phys_part = udf_rw16(mapping->pm1.part_num); pmap_type = UDF_VTOP_TYPE_PHYS; n_phys++; ump->data_part = log_part; ump->node_part = log_part; ump->fids_part = log_part; break; case 2: /* virtual/sparable/meta mapping */ map_name = mapping->pm2.part_id.id; /* volseq = udf_rw16(mapping->pm2.vol_seq_num); */ raw_phys_part = udf_rw16(mapping->pm2.part_num); pmap_type = UDF_VTOP_TYPE_UNKNOWN; len = UDF_REGID_ID_SIZE; check_name = "*UDF Virtual Partition"; if (strncmp(map_name, check_name, len) == 0) { pmap_type = UDF_VTOP_TYPE_VIRT; n_virt++; ump->node_part = log_part; break; } check_name = "*UDF Sparable Partition"; if (strncmp(map_name, check_name, len) == 0) { pmap_type = UDF_VTOP_TYPE_SPARABLE; n_spar++; ump->data_part = log_part; ump->node_part = log_part; ump->fids_part = log_part; break; } check_name = "*UDF Metadata Partition"; if (strncmp(map_name, check_name, len) == 0) { pmap_type = UDF_VTOP_TYPE_META; n_meta++; ump->node_part = log_part; ump->fids_part = log_part; break; } break; default: return EINVAL; } /* * BUGALERT: some rogue implementations use random physical * partition numbers to break other implementations so lookup * the number. */ phys_part = udf_find_raw_phys(ump, raw_phys_part); DPRINTF(VOLUMES, ("\t%d -> %d(%d) type %d\n", log_part, raw_phys_part, phys_part, pmap_type)); if (phys_part == UDF_PARTITIONS) return EINVAL; if (pmap_type == UDF_VTOP_TYPE_UNKNOWN) return EINVAL; ump->vtop [log_part] = phys_part; ump->vtop_tp[log_part] = pmap_type; pmap_pos += pmap_size; } /* not winning the beauty contest */ ump->vtop_tp[UDF_VTOP_RAWPART] = UDF_VTOP_TYPE_RAW; /* test some basic UDF assertions/requirements */ if ((n_virt > 1) || (n_spar > 1) || (n_meta > 1)) return EINVAL; if (n_virt) { if ((n_phys == 0) || n_spar || n_meta) return EINVAL; } if (n_spar + n_phys == 0) return EINVAL; /* select allocation type for each logical partition */ for (log_part = 0; log_part < n_pm; log_part++) { maps_on = ump->vtop[log_part]; switch (ump->vtop_tp[log_part]) { case UDF_VTOP_TYPE_PHYS : assert(maps_on == log_part); ump->vtop_alloc[log_part] = UDF_ALLOC_SPACEMAP; break; case UDF_VTOP_TYPE_VIRT : ump->vtop_alloc[log_part] = UDF_ALLOC_VAT; ump->vtop_alloc[maps_on] = UDF_ALLOC_SEQUENTIAL; break; case UDF_VTOP_TYPE_SPARABLE : assert(maps_on == log_part); ump->vtop_alloc[log_part] = UDF_ALLOC_SPACEMAP; break; case UDF_VTOP_TYPE_META : ump->vtop_alloc[log_part] = UDF_ALLOC_METABITMAP; if (ump->discinfo.mmc_cur & MMC_CAP_PSEUDOOVERWRITE) { /* special case for UDF 2.60 */ ump->vtop_alloc[log_part] = UDF_ALLOC_METASEQUENTIAL; ump->vtop_alloc[maps_on] = UDF_ALLOC_SEQUENTIAL; } break; default: panic("bad alloction type in udf's ump->vtop\n"); } } /* determine logical volume open/closure actions */ if (n_virt) { ump->lvopen = 0; if (ump->discinfo.last_session_state == MMC_STATE_EMPTY) ump->lvopen |= UDF_OPEN_SESSION ; ump->lvclose = UDF_WRITE_VAT; if (ump->mount_args.udfmflags & UDFMNT_CLOSESESSION) ump->lvclose |= UDF_CLOSE_SESSION; } else { /* `normal' rewritable or non sequential media */ ump->lvopen = UDF_WRITE_LVINT; ump->lvclose = UDF_WRITE_LVINT; if ((ump->discinfo.mmc_cur & MMC_CAP_REWRITABLE) == 0) ump->lvopen |= UDF_APPENDONLY_LVINT; if ((ump->discinfo.mmc_cur & MMC_CAP_PSEUDOOVERWRITE)) ump->lvopen &= ~UDF_APPENDONLY_LVINT; } /* * Determine sheduler error behaviour. For virtual partitions, update * the trackinfo; for sparable partitions replace a whole block on the * sparable table. Allways requeue. */ ump->lvreadwrite = 0; if (n_virt) ump->lvreadwrite = UDF_UPDATE_TRACKINFO; if (n_spar) ump->lvreadwrite = UDF_REMAP_BLOCK; /* * Select our sheduler */ ump->strategy = &udf_strat_rmw; if (n_virt || (ump->discinfo.mmc_cur & MMC_CAP_PSEUDOOVERWRITE)) ump->strategy = &udf_strat_sequential; if ((ump->discinfo.mmc_class == MMC_CLASS_DISC) || (ump->discinfo.mmc_class == MMC_CLASS_UNKN)) ump->strategy = &udf_strat_direct; if (n_spar) ump->strategy = &udf_strat_rmw; #if 0 /* read-only access won't benefit from the other shedulers */ if (ump->vfs_mountp->mnt_flag & MNT_RDONLY) ump->strategy = &udf_strat_direct; #endif /* print results */ DPRINTF(VOLUMES, ("\tdata partition %d\n", ump->data_part)); DPRINTF(VOLUMES, ("\t\talloc scheme %d\n", ump->vtop_alloc[ump->data_part])); DPRINTF(VOLUMES, ("\tnode partition %d\n", ump->node_part)); DPRINTF(VOLUMES, ("\t\talloc scheme %d\n", ump->vtop_alloc[ump->node_part])); DPRINTF(VOLUMES, ("\tfids partition %d\n", ump->fids_part)); DPRINTF(VOLUMES, ("\t\talloc scheme %d\n", ump->vtop_alloc[ump->fids_part])); snprintb(bits, sizeof(bits), UDFLOGVOL_BITS, ump->lvopen); DPRINTF(VOLUMES, ("\tactions on logvol open %s\n", bits)); snprintb(bits, sizeof(bits), UDFLOGVOL_BITS, ump->lvclose); DPRINTF(VOLUMES, ("\tactions on logvol close %s\n", bits)); snprintb(bits, sizeof(bits), UDFONERROR_BITS, ump->lvreadwrite); DPRINTF(VOLUMES, ("\tactions on logvol errors %s\n", bits)); DPRINTF(VOLUMES, ("\tselected sheduler `%s`\n", (ump->strategy == &udf_strat_direct) ? "Direct" : (ump->strategy == &udf_strat_sequential) ? "Sequential" : (ump->strategy == &udf_strat_rmw) ? "RMW" : "UNKNOWN!")); /* signal its OK for now */ return 0; } /* --------------------------------------------------------------------- */ /* * Update logical volume name in all structures that keep a record of it. We * use memmove since each of them might be specified as a source. * * Note that it doesn't update the VAT structure! */ static void udf_update_logvolname(struct udf_mount *ump, char *logvol_id) { struct logvol_desc *lvd = NULL; struct fileset_desc *fsd = NULL; struct udf_lv_info *lvi = NULL; DPRINTF(VOLUMES, ("Updating logical volume name\n")); lvd = ump->logical_vol; fsd = ump->fileset_desc; if (ump->implementation) lvi = &ump->implementation->_impl_use.lv_info; /* logvol's id might be specified as origional so use memmove here */ memmove(lvd->logvol_id, logvol_id, 128); if (fsd) memmove(fsd->logvol_id, logvol_id, 128); if (lvi) memmove(lvi->logvol_id, logvol_id, 128); } /* --------------------------------------------------------------------- */ void udf_inittag(struct udf_mount *ump, struct desc_tag *tag, int tagid, uint32_t sector) { assert(ump->logical_vol); tag->id = udf_rw16(tagid); tag->descriptor_ver = ump->logical_vol->tag.descriptor_ver; tag->cksum = 0; tag->reserved = 0; tag->serial_num = ump->logical_vol->tag.serial_num; tag->tag_loc = udf_rw32(sector); } uint64_t udf_advance_uniqueid(struct udf_mount *ump) { uint64_t unique_id; mutex_enter(&ump->logvol_mutex); unique_id = udf_rw64(ump->logvol_integrity->lvint_next_unique_id); if (unique_id < 0x10) unique_id = 0x10; ump->logvol_integrity->lvint_next_unique_id = udf_rw64(unique_id + 1); mutex_exit(&ump->logvol_mutex); return unique_id; } static void udf_adjust_filecount(struct udf_node *udf_node, int sign) { struct udf_mount *ump = udf_node->ump; uint32_t num_dirs, num_files; int udf_file_type; /* get file type */ if (udf_node->fe) { udf_file_type = udf_node->fe->icbtag.file_type; } else { udf_file_type = udf_node->efe->icbtag.file_type; } /* adjust file count */ mutex_enter(&ump->allocate_mutex); if (udf_file_type == UDF_ICB_FILETYPE_DIRECTORY) { num_dirs = udf_rw32(ump->logvol_info->num_directories); ump->logvol_info->num_directories = udf_rw32((num_dirs + sign)); } else { num_files = udf_rw32(ump->logvol_info->num_files); ump->logvol_info->num_files = udf_rw32((num_files + sign)); } mutex_exit(&ump->allocate_mutex); } void udf_osta_charset(struct charspec *charspec) { memset(charspec, 0, sizeof(struct charspec)); charspec->type = 0; strcpy((char *) charspec->inf, "OSTA Compressed Unicode"); } /* first call udf_set_regid and then the suffix */ void udf_set_regid(struct regid *regid, char const *name) { memset(regid, 0, sizeof(struct regid)); regid->flags = 0; /* not dirty and not protected */ strcpy((char *) regid->id, name); } void udf_add_domain_regid(struct udf_mount *ump, struct regid *regid) { uint16_t *ver; ver = (uint16_t *) regid->id_suffix; *ver = ump->logvol_info->min_udf_readver; } void udf_add_udf_regid(struct udf_mount *ump, struct regid *regid) { uint16_t *ver; ver = (uint16_t *) regid->id_suffix; *ver = ump->logvol_info->min_udf_readver; regid->id_suffix[2] = 4; /* unix */ regid->id_suffix[3] = 8; /* NetBSD */ } void udf_add_impl_regid(struct udf_mount *ump, struct regid *regid) { regid->id_suffix[0] = 4; /* unix */ regid->id_suffix[1] = 8; /* NetBSD */ } void udf_add_app_regid(struct udf_mount *ump, struct regid *regid) { regid->id_suffix[0] = APP_VERSION_MAIN; regid->id_suffix[1] = APP_VERSION_SUB; } static int udf_create_parentfid(struct udf_mount *ump, struct fileid_desc *fid, struct long_ad *parent, uint64_t unique_id) { /* the size of an empty FID is 38 but needs to be a multiple of 4 */ int fidsize = 40; udf_inittag(ump, &fid->tag, TAGID_FID, udf_rw32(parent->loc.lb_num)); fid->file_version_num = udf_rw16(1); /* UDF 2.3.4.1 */ fid->file_char = UDF_FILE_CHAR_DIR | UDF_FILE_CHAR_PAR; fid->icb = *parent; fid->icb.longad_uniqueid = udf_rw32((uint32_t) unique_id); fid->tag.desc_crc_len = udf_rw16(fidsize - UDF_DESC_TAG_LENGTH); (void) udf_validate_tag_and_crc_sums((union dscrptr *) fid); return fidsize; } /* --------------------------------------------------------------------- */ /* * Extended attribute support. UDF knows of 3 places for extended attributes: * * (a) inside the file's (e)fe in the length of the extended attribute area * before the allocation descriptors/filedata * * (b) in a file referenced by (e)fe->ext_attr_icb and * * (c) in the e(fe)'s associated stream directory that can hold various * sub-files. In the stream directory a few fixed named subfiles are reserved * for NT/Unix ACL's and OS/2 attributes. * * NOTE: Extended attributes are read randomly but allways written * *atomicaly*. For ACL's this interface is propably different but not known * to me yet. * * Order of extended attributes in a space : * ECMA 167 EAs * Non block aligned Implementation Use EAs * Block aligned Implementation Use EAs * Application Use EAs */ static int udf_impl_extattr_check(struct impl_extattr_entry *implext) { uint16_t *spos; if (strncmp(implext->imp_id.id, "*UDF", 4) == 0) { /* checksum valid? */ DPRINTF(EXTATTR, ("checking UDF impl. attr checksum\n")); spos = (uint16_t *) implext->data; if (udf_rw16(*spos) != udf_ea_cksum((uint8_t *) implext)) return EINVAL; } return 0; } static void udf_calc_impl_extattr_checksum(struct impl_extattr_entry *implext) { uint16_t *spos; if (strncmp(implext->imp_id.id, "*UDF", 4) == 0) { /* set checksum */ spos = (uint16_t *) implext->data; *spos = udf_rw16(udf_ea_cksum((uint8_t *) implext)); } } int udf_extattr_search_intern(struct udf_node *node, uint32_t sattr, char const *sattrname, uint32_t *offsetp, uint32_t *lengthp) { struct extattrhdr_desc *eahdr; struct extattr_entry *attrhdr; struct impl_extattr_entry *implext; uint32_t offset, a_l, sector_size; int32_t l_ea; uint8_t *pos; int error; /* get mountpoint */ sector_size = node->ump->discinfo.sector_size; /* get information from fe/efe */ if (node->fe) { l_ea = udf_rw32(node->fe->l_ea); eahdr = (struct extattrhdr_desc *) node->fe->data; } else { assert(node->efe); l_ea = udf_rw32(node->efe->l_ea); eahdr = (struct extattrhdr_desc *) node->efe->data; } /* something recorded here? */ if (l_ea == 0) return ENOENT; /* check extended attribute tag; what to do if it fails? */ error = udf_check_tag(eahdr); if (error) return EINVAL; if (udf_rw16(eahdr->tag.id) != TAGID_EXTATTR_HDR) return EINVAL; error = udf_check_tag_payload(eahdr, sizeof(struct extattrhdr_desc)); if (error) return EINVAL; DPRINTF(EXTATTR, ("Found %d bytes of extended attributes\n", l_ea)); /* looking for Ecma-167 attributes? */ offset = sizeof(struct extattrhdr_desc); /* looking for either implemenation use or application use */ if (sattr == 2048) { /* [4/48.10.8] */ offset = udf_rw32(eahdr->impl_attr_loc); if (offset == UDF_IMPL_ATTR_LOC_NOT_PRESENT) return ENOENT; } if (sattr == 65536) { /* [4/48.10.9] */ offset = udf_rw32(eahdr->appl_attr_loc); if (offset == UDF_APPL_ATTR_LOC_NOT_PRESENT) return ENOENT; } /* paranoia check offset and l_ea */ if (l_ea + offset >= sector_size - sizeof(struct extattr_entry)) return EINVAL; DPRINTF(EXTATTR, ("Starting at offset %d\n", offset)); /* find our extended attribute */ l_ea -= offset; pos = (uint8_t *) eahdr + offset; while (l_ea >= sizeof(struct extattr_entry)) { DPRINTF(EXTATTR, ("%d extended attr bytes left\n", l_ea)); attrhdr = (struct extattr_entry *) pos; implext = (struct impl_extattr_entry *) pos; /* get complete attribute length and check for roque values */ a_l = udf_rw32(attrhdr->a_l); DPRINTF(EXTATTR, ("attribute %d:%d, len %d/%d\n", udf_rw32(attrhdr->type), attrhdr->subtype, a_l, l_ea)); if ((a_l == 0) || (a_l > l_ea)) return EINVAL; if (attrhdr->type != sattr) goto next_attribute; /* we might have found it! */ if (attrhdr->type < 2048) { /* Ecma-167 attribute */ *offsetp = offset; *lengthp = a_l; return 0; /* success */ } /* * Implementation use and application use extended attributes * have a name to identify. They share the same structure only * UDF implementation use extended attributes have a checksum * we need to check */ DPRINTF(EXTATTR, ("named attribute %s\n", implext->imp_id.id)); if (strcmp(implext->imp_id.id, sattrname) == 0) { /* we have found our appl/implementation attribute */ *offsetp = offset; *lengthp = a_l; return 0; /* success */ } next_attribute: /* next attribute */ pos += a_l; l_ea -= a_l; offset += a_l; } /* not found */ return ENOENT; } static void udf_extattr_insert_internal(struct udf_mount *ump, union dscrptr *dscr, struct extattr_entry *extattr) { struct file_entry *fe; struct extfile_entry *efe; struct extattrhdr_desc *extattrhdr; struct impl_extattr_entry *implext; uint32_t impl_attr_loc, appl_attr_loc, l_ea, a_l, exthdr_len; uint32_t *l_eap, l_ad; uint16_t *spos; uint8_t *bpos, *data; if (udf_rw16(dscr->tag.id) == TAGID_FENTRY) { fe = &dscr->fe; data = fe->data; l_eap = &fe->l_ea; l_ad = udf_rw32(fe->l_ad); } else if (udf_rw16(dscr->tag.id) == TAGID_EXTFENTRY) { efe = &dscr->efe; data = efe->data; l_eap = &efe->l_ea; l_ad = udf_rw32(efe->l_ad); } else { panic("Bad tag passed to udf_extattr_insert_internal"); } /* can't append already written to file descriptors yet */ assert(l_ad == 0); __USE(l_ad); /* should have a header! */ extattrhdr = (struct extattrhdr_desc *) data; l_ea = udf_rw32(*l_eap); if (l_ea == 0) { /* create empty extended attribute header */ exthdr_len = sizeof(struct extattrhdr_desc); udf_inittag(ump, &extattrhdr->tag, TAGID_EXTATTR_HDR, /* loc */ 0); extattrhdr->impl_attr_loc = udf_rw32(exthdr_len); extattrhdr->appl_attr_loc = udf_rw32(exthdr_len); extattrhdr->tag.desc_crc_len = udf_rw16(8); /* record extended attribute header length */ l_ea = exthdr_len; *l_eap = udf_rw32(l_ea); } /* extract locations */ impl_attr_loc = udf_rw32(extattrhdr->impl_attr_loc); appl_attr_loc = udf_rw32(extattrhdr->appl_attr_loc); if (impl_attr_loc == UDF_IMPL_ATTR_LOC_NOT_PRESENT) impl_attr_loc = l_ea; if (appl_attr_loc == UDF_IMPL_ATTR_LOC_NOT_PRESENT) appl_attr_loc = l_ea; /* Ecma 167 EAs */ if (udf_rw32(extattr->type) < 2048) { assert(impl_attr_loc == l_ea); assert(appl_attr_loc == l_ea); } /* implementation use extended attributes */ if (udf_rw32(extattr->type) == 2048) { assert(appl_attr_loc == l_ea); /* calculate and write extended attribute header checksum */ implext = (struct impl_extattr_entry *) extattr; assert(udf_rw32(implext->iu_l) == 4); /* [UDF 3.3.4.5] */ spos = (uint16_t *) implext->data; *spos = udf_rw16(udf_ea_cksum((uint8_t *) implext)); } /* application use extended attributes */ assert(udf_rw32(extattr->type) != 65536); assert(appl_attr_loc == l_ea); /* append the attribute at the end of the current space */ bpos = data + udf_rw32(*l_eap); a_l = udf_rw32(extattr->a_l); /* update impl. attribute locations */ if (udf_rw32(extattr->type) < 2048) { impl_attr_loc = l_ea + a_l; appl_attr_loc = l_ea + a_l; } if (udf_rw32(extattr->type) == 2048) { appl_attr_loc = l_ea + a_l; } /* copy and advance */ memcpy(bpos, extattr, a_l); l_ea += a_l; *l_eap = udf_rw32(l_ea); /* do the `dance` again backwards */ if (udf_rw16(ump->logical_vol->tag.descriptor_ver) != 2) { if (impl_attr_loc == l_ea) impl_attr_loc = UDF_IMPL_ATTR_LOC_NOT_PRESENT; if (appl_attr_loc == l_ea) appl_attr_loc = UDF_APPL_ATTR_LOC_NOT_PRESENT; } /* store offsets */ extattrhdr->impl_attr_loc = udf_rw32(impl_attr_loc); extattrhdr->appl_attr_loc = udf_rw32(appl_attr_loc); } /* --------------------------------------------------------------------- */ static int udf_update_lvid_from_vat_extattr(struct udf_node *vat_node) { struct udf_mount *ump; struct udf_logvol_info *lvinfo; struct impl_extattr_entry *implext; struct vatlvext_extattr_entry lvext; const char *extstr = "*UDF VAT LVExtension"; uint64_t vat_uniqueid; uint32_t offset, a_l; uint8_t *ea_start, *lvextpos; int error; /* get mountpoint and lvinfo */ ump = vat_node->ump; lvinfo = ump->logvol_info; /* get information from fe/efe */ if (vat_node->fe) { vat_uniqueid = udf_rw64(vat_node->fe->unique_id); ea_start = vat_node->fe->data; } else { vat_uniqueid = udf_rw64(vat_node->efe->unique_id); ea_start = vat_node->efe->data; } error = udf_extattr_search_intern(vat_node, 2048, extstr, &offset, &a_l); if (error) return error; implext = (struct impl_extattr_entry *) (ea_start + offset); error = udf_impl_extattr_check(implext); if (error) return error; /* paranoia */ if (a_l != sizeof(*implext) -1 + udf_rw32(implext->iu_l) + sizeof(lvext)) { DPRINTF(VOLUMES, ("VAT LVExtension size doesn't compute\n")); return EINVAL; } /* * we have found our "VAT LVExtension attribute. BUT due to a * bug in the specification it might not be word aligned so * copy first to avoid panics on some machines (!!) */ DPRINTF(VOLUMES, ("Found VAT LVExtension attr\n")); lvextpos = implext->data + udf_rw32(implext->iu_l); memcpy(&lvext, lvextpos, sizeof(lvext)); /* check if it was updated the last time */ if (udf_rw64(lvext.unique_id_chk) == vat_uniqueid) { lvinfo->num_files = lvext.num_files; lvinfo->num_directories = lvext.num_directories; udf_update_logvolname(ump, lvext.logvol_id); } else { DPRINTF(VOLUMES, ("VAT LVExtension out of date\n")); /* replace VAT LVExt by free space EA */ memset(implext->imp_id.id, 0, UDF_REGID_ID_SIZE); strcpy(implext->imp_id.id, "*UDF FreeEASpace"); udf_calc_impl_extattr_checksum(implext); } return 0; } static int udf_update_vat_extattr_from_lvid(struct udf_node *vat_node) { struct udf_mount *ump; struct udf_logvol_info *lvinfo; struct impl_extattr_entry *implext; struct vatlvext_extattr_entry lvext; const char *extstr = "*UDF VAT LVExtension"; uint64_t vat_uniqueid; uint32_t offset, a_l; uint8_t *ea_start, *lvextpos; int error; /* get mountpoint and lvinfo */ ump = vat_node->ump; lvinfo = ump->logvol_info; /* get information from fe/efe */ if (vat_node->fe) { vat_uniqueid = udf_rw64(vat_node->fe->unique_id); ea_start = vat_node->fe->data; } else { vat_uniqueid = udf_rw64(vat_node->efe->unique_id); ea_start = vat_node->efe->data; } error = udf_extattr_search_intern(vat_node, 2048, extstr, &offset, &a_l); if (error) return error; /* found, it existed */ /* paranoia */ implext = (struct impl_extattr_entry *) (ea_start + offset); error = udf_impl_extattr_check(implext); if (error) { DPRINTF(VOLUMES, ("VAT LVExtension bad on update\n")); return error; } /* it is correct */ /* * we have found our "VAT LVExtension attribute. BUT due to a * bug in the specification it might not be word aligned so * copy first to avoid panics on some machines (!!) */ DPRINTF(VOLUMES, ("Updating VAT LVExtension attr\n")); lvextpos = implext->data + udf_rw32(implext->iu_l); lvext.unique_id_chk = vat_uniqueid; lvext.num_files = lvinfo->num_files; lvext.num_directories = lvinfo->num_directories; memmove(lvext.logvol_id, ump->logical_vol->logvol_id, 128); memcpy(lvextpos, &lvext, sizeof(lvext)); return 0; } /* --------------------------------------------------------------------- */ int udf_vat_read(struct udf_node *vat_node, uint8_t *blob, int size, uint32_t offset) { struct udf_mount *ump = vat_node->ump; if (offset + size > ump->vat_offset + ump->vat_entries * 4) return EINVAL; memcpy(blob, ump->vat_table + offset, size); return 0; } int udf_vat_write(struct udf_node *vat_node, uint8_t *blob, int size, uint32_t offset) { struct udf_mount *ump = vat_node->ump; uint32_t offset_high; uint8_t *new_vat_table; /* extent VAT allocation if needed */ offset_high = offset + size; if (offset_high >= ump->vat_table_alloc_len) { /* realloc */ new_vat_table = realloc(ump->vat_table, ump->vat_table_alloc_len + UDF_VAT_CHUNKSIZE, M_UDFVOLD, M_WAITOK | M_CANFAIL); if (!new_vat_table) { printf("udf_vat_write: can't extent VAT, out of mem\n"); return ENOMEM; } ump->vat_table = new_vat_table; ump->vat_table_alloc_len += UDF_VAT_CHUNKSIZE; } ump->vat_table_len = MAX(ump->vat_table_len, offset_high); memcpy(ump->vat_table + offset, blob, size); return 0; } /* --------------------------------------------------------------------- */ /* TODO support previous VAT location writeout */ static int udf_update_vat_descriptor(struct udf_mount *ump) { struct udf_node *vat_node = ump->vat_node; struct udf_logvol_info *lvinfo = ump->logvol_info; struct icb_tag *icbtag; struct udf_oldvat_tail *oldvat_tl; struct udf_vat *vat; uint64_t unique_id; uint32_t lb_size; uint8_t *raw_vat; int filetype, error; KASSERT(vat_node); KASSERT(lvinfo); lb_size = udf_rw32(ump->logical_vol->lb_size); /* get our new unique_id */ unique_id = udf_advance_uniqueid(ump); /* get information from fe/efe */ if (vat_node->fe) { icbtag = &vat_node->fe->icbtag; vat_node->fe->unique_id = udf_rw64(unique_id); } else { icbtag = &vat_node->efe->icbtag; vat_node->efe->unique_id = udf_rw64(unique_id); } /* Check icb filetype! it has to be 0 or UDF_ICB_FILETYPE_VAT */ filetype = icbtag->file_type; KASSERT((filetype == 0) || (filetype == UDF_ICB_FILETYPE_VAT)); /* allocate piece to process head or tail of VAT file */ raw_vat = malloc(lb_size, M_TEMP, M_WAITOK); if (filetype == 0) { /* * Update "*UDF VAT LVExtension" extended attribute from the * lvint if present. */ udf_update_vat_extattr_from_lvid(vat_node); /* setup identifying regid */ oldvat_tl = (struct udf_oldvat_tail *) raw_vat; memset(oldvat_tl, 0, sizeof(struct udf_oldvat_tail)); udf_set_regid(&oldvat_tl->id, "*UDF Virtual Alloc Tbl"); udf_add_udf_regid(ump, &oldvat_tl->id); oldvat_tl->prev_vat = udf_rw32(0xffffffff); /* write out new tail of virtual allocation table file */ error = udf_vat_write(vat_node, raw_vat, sizeof(struct udf_oldvat_tail), ump->vat_entries * 4); } else { /* compose the VAT2 header */ vat = (struct udf_vat *) raw_vat; memset(vat, 0, sizeof(struct udf_vat)); vat->header_len = udf_rw16(152); /* as per spec */ vat->impl_use_len = udf_rw16(0); memmove(vat->logvol_id, ump->logical_vol->logvol_id, 128); vat->prev_vat = udf_rw32(0xffffffff); vat->num_files = lvinfo->num_files; vat->num_directories = lvinfo->num_directories; vat->min_udf_readver = lvinfo->min_udf_readver; vat->min_udf_writever = lvinfo->min_udf_writever; vat->max_udf_writever = lvinfo->max_udf_writever; error = udf_vat_write(vat_node, raw_vat, sizeof(struct udf_vat), 0); } free(raw_vat, M_TEMP); return error; /* success! */ } int udf_writeout_vat(struct udf_mount *ump) { struct udf_node *vat_node = ump->vat_node; int error; KASSERT(vat_node); DPRINTF(CALL, ("udf_writeout_vat\n")); // mutex_enter(&ump->allocate_mutex); udf_update_vat_descriptor(ump); /* write out the VAT contents ; TODO intelligent writing */ error = vn_rdwr(UIO_WRITE, vat_node->vnode, ump->vat_table, ump->vat_table_len, 0, UIO_SYSSPACE, 0, FSCRED, NULL, NULL); if (error) { printf("udf_writeout_vat: failed to write out VAT contents\n"); goto out; } // mutex_exit(&ump->allocate_mutex); error = vflushbuf(ump->vat_node->vnode, FSYNC_WAIT); if (error) goto out; error = VOP_FSYNC(ump->vat_node->vnode, FSCRED, FSYNC_WAIT, 0, 0); if (error) printf("udf_writeout_vat: error writing VAT node!\n"); out: return error; } /* --------------------------------------------------------------------- */ /* * Read in relevant pieces of VAT file and check if its indeed a VAT file * descriptor. If OK, read in complete VAT file. */ static int udf_check_for_vat(struct udf_node *vat_node) { struct udf_mount *ump; struct icb_tag *icbtag; struct timestamp *mtime; struct udf_vat *vat; struct udf_oldvat_tail *oldvat_tl; struct udf_logvol_info *lvinfo; uint64_t unique_id; uint32_t vat_length; uint32_t vat_offset, vat_entries, vat_table_alloc_len; uint32_t sector_size; uint32_t *raw_vat; uint8_t *vat_table; char *regid_name; int filetype; int error; /* vat_length is really 64 bits though impossible */ DPRINTF(VOLUMES, ("Checking for VAT\n")); if (!vat_node) return ENOENT; /* get mount info */ ump = vat_node->ump; sector_size = udf_rw32(ump->logical_vol->lb_size); /* check assertions */ assert(vat_node->fe || vat_node->efe); assert(ump->logvol_integrity); /* set vnode type to regular file or we can't read from it! */ vat_node->vnode->v_type = VREG; /* get information from fe/efe */ if (vat_node->fe) { vat_length = udf_rw64(vat_node->fe->inf_len); icbtag = &vat_node->fe->icbtag; mtime = &vat_node->fe->mtime; unique_id = udf_rw64(vat_node->fe->unique_id); } else { vat_length = udf_rw64(vat_node->efe->inf_len); icbtag = &vat_node->efe->icbtag; mtime = &vat_node->efe->mtime; unique_id = udf_rw64(vat_node->efe->unique_id); } /* Check icb filetype! it has to be 0 or UDF_ICB_FILETYPE_VAT */ filetype = icbtag->file_type; if ((filetype != 0) && (filetype != UDF_ICB_FILETYPE_VAT)) return ENOENT; DPRINTF(VOLUMES, ("\tPossible VAT length %d\n", vat_length)); vat_table_alloc_len = ((vat_length + UDF_VAT_CHUNKSIZE-1) / UDF_VAT_CHUNKSIZE) * UDF_VAT_CHUNKSIZE; vat_table = malloc(vat_table_alloc_len, M_UDFVOLD, M_CANFAIL | M_WAITOK); if (vat_table == NULL) { printf("allocation of %d bytes failed for VAT\n", vat_table_alloc_len); return ENOMEM; } /* allocate piece to read in head or tail of VAT file */ raw_vat = malloc(sector_size, M_TEMP, M_WAITOK); /* * check contents of the file if its the old 1.50 VAT table format. * Its notoriously broken and allthough some implementations support an * extention as defined in the UDF 1.50 errata document, its doubtfull * to be useable since a lot of implementations don't maintain it. */ lvinfo = ump->logvol_info; if (filetype == 0) { /* definition */ vat_offset = 0; vat_entries = (vat_length-36)/4; /* read in tail of virtual allocation table file */ error = vn_rdwr(UIO_READ, vat_node->vnode, (uint8_t *) raw_vat, sizeof(struct udf_oldvat_tail), vat_entries * 4, UIO_SYSSPACE, IO_SYNC | IO_NODELOCKED, FSCRED, NULL, NULL); if (error) goto out; /* check 1.50 VAT */ oldvat_tl = (struct udf_oldvat_tail *) raw_vat; regid_name = (char *) oldvat_tl->id.id; error = strncmp(regid_name, "*UDF Virtual Alloc Tbl", 22); if (error) { DPRINTF(VOLUMES, ("VAT format 1.50 rejected\n")); error = ENOENT; goto out; } /* * update LVID from "*UDF VAT LVExtension" extended attribute * if present. */ udf_update_lvid_from_vat_extattr(vat_node); } else { /* read in head of virtual allocation table file */ error = vn_rdwr(UIO_READ, vat_node->vnode, (uint8_t *) raw_vat, sizeof(struct udf_vat), 0, UIO_SYSSPACE, IO_SYNC | IO_NODELOCKED, FSCRED, NULL, NULL); if (error) goto out; /* definition */ vat = (struct udf_vat *) raw_vat; vat_offset = vat->header_len; vat_entries = (vat_length - vat_offset)/4; assert(lvinfo); lvinfo->num_files = vat->num_files; lvinfo->num_directories = vat->num_directories; lvinfo->min_udf_readver = vat->min_udf_readver; lvinfo->min_udf_writever = vat->min_udf_writever; lvinfo->max_udf_writever = vat->max_udf_writever; udf_update_logvolname(ump, vat->logvol_id); } /* read in complete VAT file */ error = vn_rdwr(UIO_READ, vat_node->vnode, vat_table, vat_length, 0, UIO_SYSSPACE, IO_SYNC | IO_NODELOCKED, FSCRED, NULL, NULL); if (error) printf("read in of complete VAT file failed (error %d)\n", error); if (error) goto out; DPRINTF(VOLUMES, ("VAT format accepted, marking it closed\n")); ump->logvol_integrity->lvint_next_unique_id = udf_rw64(unique_id); ump->logvol_integrity->integrity_type = udf_rw32(UDF_INTEGRITY_CLOSED); ump->logvol_integrity->time = *mtime; ump->vat_table_len = vat_length; ump->vat_table_alloc_len = vat_table_alloc_len; ump->vat_table = vat_table; ump->vat_offset = vat_offset; ump->vat_entries = vat_entries; ump->vat_last_free_lb = 0; /* start at beginning */ out: if (error) { if (vat_table) free(vat_table, M_UDFVOLD); } free(raw_vat, M_TEMP); return error; } /* --------------------------------------------------------------------- */ static int udf_search_vat(struct udf_mount *ump, union udf_pmap *mapping) { struct udf_node *vat_node; struct long_ad icb_loc; uint32_t early_vat_loc, vat_loc; int error; /* mapping info not needed */ mapping = mapping; vat_loc = ump->last_possible_vat_location; early_vat_loc = vat_loc - 256; /* 8 blocks of 32 sectors */ DPRINTF(VOLUMES, ("1) last possible %d, early_vat_loc %d \n", vat_loc, early_vat_loc)); early_vat_loc = MAX(early_vat_loc, ump->first_possible_vat_location); DPRINTF(VOLUMES, ("2) last possible %d, early_vat_loc %d \n", vat_loc, early_vat_loc)); /* start looking from the end of the range */ do { DPRINTF(VOLUMES, ("Checking for VAT at sector %d\n", vat_loc)); icb_loc.loc.part_num = udf_rw16(UDF_VTOP_RAWPART); icb_loc.loc.lb_num = udf_rw32(vat_loc); error = udf_get_node(ump, &icb_loc, &vat_node); if (!error) { error = udf_check_for_vat(vat_node); DPRINTFIF(VOLUMES, !error, ("VAT accepted at %d\n", vat_loc)); if (!error) break; } if (vat_node) { vput(vat_node->vnode); vat_node = NULL; } vat_loc--; /* walk backwards */ } while (vat_loc >= early_vat_loc); /* keep our VAT node around */ if (vat_node) { UDF_SET_SYSTEMFILE(vat_node->vnode); ump->vat_node = vat_node; } return error; } /* --------------------------------------------------------------------- */ static int udf_read_sparables(struct udf_mount *ump, union udf_pmap *mapping) { union dscrptr *dscr; struct part_map_spare *pms = &mapping->pms; uint32_t lb_num; int spar, error; /* * The partition mapping passed on to us specifies the information we * need to locate and initialise the sparable partition mapping * information we need. */ DPRINTF(VOLUMES, ("Read sparable table\n")); ump->sparable_packet_size = udf_rw16(pms->packet_len); KASSERT(ump->sparable_packet_size >= ump->packet_size); /* XXX */ for (spar = 0; spar < pms->n_st; spar++) { lb_num = pms->st_loc[spar]; DPRINTF(VOLUMES, ("Checking for sparing table %d\n", lb_num)); error = udf_read_phys_dscr(ump, lb_num, M_UDFVOLD, &dscr); if (!error && dscr) { if (udf_rw16(dscr->tag.id) == TAGID_SPARING_TABLE) { if (ump->sparing_table) free(ump->sparing_table, M_UDFVOLD); ump->sparing_table = &dscr->spt; dscr = NULL; DPRINTF(VOLUMES, ("Sparing table accepted (%d entries)\n", udf_rw16(ump->sparing_table->rt_l))); break; /* we're done */ } } if (dscr) free(dscr, M_UDFVOLD); } if (ump->sparing_table) return 0; return ENOENT; } /* --------------------------------------------------------------------- */ static int udf_read_metadata_nodes(struct udf_mount *ump, union udf_pmap *mapping) { struct part_map_meta *pmm = &mapping->pmm; struct long_ad icb_loc; struct vnode *vp; uint16_t raw_phys_part, phys_part; int error; /* * BUGALERT: some rogue implementations use random physical * partition numbers to break other implementations so lookup * the number. */ /* extract our allocation parameters set up on format */ ump->metadata_alloc_unit_size = udf_rw32(mapping->pmm.alloc_unit_size); ump->metadata_alignment_unit_size = udf_rw16(mapping->pmm.alignment_unit_size); ump->metadata_flags = mapping->pmm.flags; DPRINTF(VOLUMES, ("Reading in Metadata files\n")); raw_phys_part = udf_rw16(pmm->part_num); phys_part = udf_find_raw_phys(ump, raw_phys_part); icb_loc.loc.part_num = udf_rw16(phys_part); DPRINTF(VOLUMES, ("Metadata file\n")); icb_loc.loc.lb_num = pmm->meta_file_lbn; error = udf_get_node(ump, &icb_loc, &ump->metadata_node); if (ump->metadata_node) { vp = ump->metadata_node->vnode; UDF_SET_SYSTEMFILE(vp); } icb_loc.loc.lb_num = pmm->meta_mirror_file_lbn; if (icb_loc.loc.lb_num != -1) { DPRINTF(VOLUMES, ("Metadata copy file\n")); error = udf_get_node(ump, &icb_loc, &ump->metadatamirror_node); if (ump->metadatamirror_node) { vp = ump->metadatamirror_node->vnode; UDF_SET_SYSTEMFILE(vp); } } icb_loc.loc.lb_num = pmm->meta_bitmap_file_lbn; if (icb_loc.loc.lb_num != -1) { DPRINTF(VOLUMES, ("Metadata bitmap file\n")); error = udf_get_node(ump, &icb_loc, &ump->metadatabitmap_node); if (ump->metadatabitmap_node) { vp = ump->metadatabitmap_node->vnode; UDF_SET_SYSTEMFILE(vp); } } /* if we're mounting read-only we relax the requirements */ if (ump->vfs_mountp->mnt_flag & MNT_RDONLY) { error = EFAULT; if (ump->metadata_node) error = 0; if ((ump->metadata_node == NULL) && (ump->metadatamirror_node)) { printf( "udf mount: Metadata file not readable, " "substituting Metadata copy file\n"); ump->metadata_node = ump->metadatamirror_node; ump->metadatamirror_node = NULL; error = 0; } } else { /* mounting read/write */ /* XXX DISABLED! metadata writing is not working yet XXX */ if (error) error = EROFS; } DPRINTFIF(VOLUMES, error, ("udf mount: failed to read " "metadata files\n")); return error; } /* --------------------------------------------------------------------- */ int udf_read_vds_tables(struct udf_mount *ump) { union udf_pmap *mapping; /* struct udf_args *args = &ump->mount_args; */ uint32_t n_pm; uint32_t log_part; uint8_t *pmap_pos; int pmap_size; int error; /* Iterate (again) over the part mappings for locations */ n_pm = udf_rw32(ump->logical_vol->n_pm); /* num partmaps */ pmap_pos = ump->logical_vol->maps; for (log_part = 0; log_part < n_pm; log_part++) { mapping = (union udf_pmap *) pmap_pos; switch (ump->vtop_tp[log_part]) { case UDF_VTOP_TYPE_PHYS : /* nothing */ break; case UDF_VTOP_TYPE_VIRT : /* search and load VAT */ error = udf_search_vat(ump, mapping); if (error) return ENOENT; break; case UDF_VTOP_TYPE_SPARABLE : /* load one of the sparable tables */ error = udf_read_sparables(ump, mapping); if (error) return ENOENT; break; case UDF_VTOP_TYPE_META : /* load the associated file descriptors */ error = udf_read_metadata_nodes(ump, mapping); if (error) return ENOENT; break; default: break; } pmap_size = pmap_pos[1]; pmap_pos += pmap_size; } /* read in and check unallocated and free space info if writing */ if ((ump->vfs_mountp->mnt_flag & MNT_RDONLY) == 0) { error = udf_read_physical_partition_spacetables(ump); if (error) return error; /* also read in metadata partition spacebitmap if defined */ error = udf_read_metadata_partition_spacetable(ump); return error; } return 0; } /* --------------------------------------------------------------------- */ int udf_read_rootdirs(struct udf_mount *ump) { union dscrptr *dscr; /* struct udf_args *args = &ump->mount_args; */ struct udf_node *rootdir_node, *streamdir_node; struct long_ad fsd_loc, *dir_loc; uint32_t lb_num, dummy; uint32_t fsd_len; int dscr_type; int error; /* TODO implement FSD reading in separate function like integrity? */ /* get fileset descriptor sequence */ fsd_loc = ump->logical_vol->lv_fsd_loc; fsd_len = udf_rw32(fsd_loc.len); dscr = NULL; error = 0; while (fsd_len || error) { DPRINTF(VOLUMES, ("fsd_len = %d\n", fsd_len)); /* translate fsd_loc to lb_num */ error = udf_translate_vtop(ump, &fsd_loc, &lb_num, &dummy); if (error) break; DPRINTF(VOLUMES, ("Reading FSD at lb %d\n", lb_num)); error = udf_read_phys_dscr(ump, lb_num, M_UDFVOLD, &dscr); /* end markers */ if (error || (dscr == NULL)) break; /* analyse */ dscr_type = udf_rw16(dscr->tag.id); if (dscr_type == TAGID_TERM) break; if (dscr_type != TAGID_FSD) { free(dscr, M_UDFVOLD); return ENOENT; } /* * TODO check for multiple fileset descriptors; its only * picking the last now. Also check for FSD * correctness/interpretability */ /* update */ if (ump->fileset_desc) { free(ump->fileset_desc, M_UDFVOLD); } ump->fileset_desc = &dscr->fsd; dscr = NULL; /* continue to the next fsd */ fsd_len -= ump->discinfo.sector_size; fsd_loc.loc.lb_num = udf_rw32(udf_rw32(fsd_loc.loc.lb_num)+1); /* follow up to fsd->next_ex (long_ad) if its not null */ if (udf_rw32(ump->fileset_desc->next_ex.len)) { DPRINTF(VOLUMES, ("follow up FSD extent\n")); fsd_loc = ump->fileset_desc->next_ex; fsd_len = udf_rw32(ump->fileset_desc->next_ex.len); } } if (dscr) free(dscr, M_UDFVOLD); /* there has to be one */ if (ump->fileset_desc == NULL) return ENOENT; DPRINTF(VOLUMES, ("FSD read in fine\n")); DPRINTF(VOLUMES, ("Updating fsd logical volume id\n")); udf_update_logvolname(ump, ump->logical_vol->logvol_id); /* * Now the FSD is known, read in the rootdirectory and if one exists, * the system stream dir. Some files in the system streamdir are not * wanted in this implementation since they are not maintained. If * writing is enabled we'll delete these files if they exist. */ rootdir_node = streamdir_node = NULL; dir_loc = NULL; /* try to read in the rootdir */ dir_loc = &ump->fileset_desc->rootdir_icb; error = udf_get_node(ump, dir_loc, &rootdir_node); if (error) return ENOENT; /* aparently it read in fine */ /* * Try the system stream directory; not very likely in the ones we * test, but for completeness. */ dir_loc = &ump->fileset_desc->streamdir_icb; if (udf_rw32(dir_loc->len)) { printf("udf_read_rootdirs: streamdir defined "); error = udf_get_node(ump, dir_loc, &streamdir_node); if (error) { printf("but error in streamdir reading\n"); } else { printf("but ignored\n"); /* * TODO process streamdir `baddies' i.e. files we dont * want if R/W */ } } DPRINTF(VOLUMES, ("Rootdir(s) read in fine\n")); /* release the vnodes again; they'll be auto-recycled later */ if (streamdir_node) { vput(streamdir_node->vnode); } if (rootdir_node) { vput(rootdir_node->vnode); } return 0; } /* --------------------------------------------------------------------- */ /* To make absolutely sure we are NOT returning zero, add one :) */ long udf_get_node_id(const struct long_ad *icbptr) { /* ought to be enough since each mountpoint has its own chain */ return udf_rw32(icbptr->loc.lb_num) + 1; } int udf_compare_icb(const struct long_ad *a, const struct long_ad *b) { if (udf_rw16(a->loc.part_num) < udf_rw16(b->loc.part_num)) return -1; if (udf_rw16(a->loc.part_num) > udf_rw16(b->loc.part_num)) return 1; if (udf_rw32(a->loc.lb_num) < udf_rw32(b->loc.lb_num)) return -1; if (udf_rw32(a->loc.lb_num) > udf_rw32(b->loc.lb_num)) return 1; return 0; } static int udf_compare_rbnodes(void *ctx, const void *a, const void *b) { const struct udf_node *a_node = a; const struct udf_node *b_node = b; return udf_compare_icb(&a_node->loc, &b_node->loc); } static int udf_compare_rbnode_icb(void *ctx, const void *a, const void *key) { const struct udf_node *a_node = a; const struct long_ad * const icb = key; return udf_compare_icb(&a_node->loc, icb); } static const rb_tree_ops_t udf_node_rbtree_ops = { .rbto_compare_nodes = udf_compare_rbnodes, .rbto_compare_key = udf_compare_rbnode_icb, .rbto_node_offset = offsetof(struct udf_node, rbnode), .rbto_context = NULL }; void udf_init_nodes_tree(struct udf_mount *ump) { rb_tree_init(&ump->udf_node_tree, &udf_node_rbtree_ops); } /* --------------------------------------------------------------------- */ static int udf_validate_session_start(struct udf_mount *ump) { struct mmc_trackinfo trackinfo; struct vrs_desc *vrs; uint32_t tracknr, sessionnr, sector, sector_size; uint32_t iso9660_vrs, write_track_start; uint8_t *buffer, *blank, *pos; int blks, max_sectors, vrs_len; int error; /* disc appendable? */ if (ump->discinfo.disc_state == MMC_STATE_FULL) return EROFS; /* already written here? if so, there should be an ISO VDS */ if (ump->discinfo.last_session_state == MMC_STATE_INCOMPLETE) return 0; /* * Check if the first track of the session is blank and if so, copy or * create a dummy ISO descriptor so the disc is valid again. */ tracknr = ump->discinfo.first_track_last_session; memset(&trackinfo, 0, sizeof(struct mmc_trackinfo)); trackinfo.tracknr = tracknr; error = udf_update_trackinfo(ump, &trackinfo); if (error) return error; udf_dump_trackinfo(&trackinfo); KASSERT(trackinfo.flags & (MMC_TRACKINFO_BLANK | MMC_TRACKINFO_RESERVED)); KASSERT(trackinfo.sessionnr > 1); KASSERT(trackinfo.flags & MMC_TRACKINFO_NWA_VALID); write_track_start = trackinfo.next_writable; /* we have to copy the ISO VRS from a former session */ DPRINTF(VOLUMES, ("validate_session_start: " "blank or reserved track, copying VRS\n")); /* sessionnr should be the session we're mounting */ sessionnr = ump->mount_args.sessionnr; /* start at the first track */ tracknr = ump->discinfo.first_track; while (tracknr <= ump->discinfo.num_tracks) { trackinfo.tracknr = tracknr; error = udf_update_trackinfo(ump, &trackinfo); if (error) { DPRINTF(VOLUMES, ("failed to get trackinfo; aborting\n")); return error; } if (trackinfo.sessionnr == sessionnr) break; tracknr++; } if (trackinfo.sessionnr != sessionnr) { DPRINTF(VOLUMES, ("failed to get trackinfo; aborting\n")); return ENOENT; } DPRINTF(VOLUMES, ("found possible former ISO VRS at\n")); udf_dump_trackinfo(&trackinfo); /* * location of iso9660 vrs is defined as first sector AFTER 32kb, * minimum ISO `sector size' 2048 */ sector_size = ump->discinfo.sector_size; iso9660_vrs = ((32*1024 + sector_size - 1) / sector_size) + trackinfo.track_start; buffer = malloc(UDF_ISO_VRS_SIZE, M_TEMP, M_WAITOK); max_sectors = UDF_ISO_VRS_SIZE / sector_size; blks = MAX(1, 2048 / sector_size); error = 0; for (sector = 0; sector < max_sectors; sector += blks) { pos = buffer + sector * sector_size; error = udf_read_phys_sectors(ump, UDF_C_DSCR, pos, iso9660_vrs + sector, blks); if (error) break; /* check this ISO descriptor */ vrs = (struct vrs_desc *) pos; DPRINTF(VOLUMES, ("got VRS id `%4s`\n", vrs->identifier)); if (strncmp(vrs->identifier, VRS_CD001, 5) == 0) continue; if (strncmp(vrs->identifier, VRS_CDW02, 5) == 0) continue; if (strncmp(vrs->identifier, VRS_BEA01, 5) == 0) continue; if (strncmp(vrs->identifier, VRS_NSR02, 5) == 0) continue; if (strncmp(vrs->identifier, VRS_NSR03, 5) == 0) continue; if (strncmp(vrs->identifier, VRS_TEA01, 5) == 0) break; /* now what? for now, end of sequence */ break; } vrs_len = sector + blks; if (error) { DPRINTF(VOLUMES, ("error reading old ISO VRS\n")); DPRINTF(VOLUMES, ("creating minimal ISO VRS\n")); memset(buffer, 0, UDF_ISO_VRS_SIZE); vrs = (struct vrs_desc *) (buffer); vrs->struct_type = 0; vrs->version = 1; memcpy(vrs->identifier,VRS_BEA01, 5); vrs = (struct vrs_desc *) (buffer + 2048); vrs->struct_type = 0; vrs->version = 1; if (udf_rw16(ump->logical_vol->tag.descriptor_ver) == 2) { memcpy(vrs->identifier,VRS_NSR02, 5); } else { memcpy(vrs->identifier,VRS_NSR03, 5); } vrs = (struct vrs_desc *) (buffer + 4096); vrs->struct_type = 0; vrs->version = 1; memcpy(vrs->identifier, VRS_TEA01, 5); vrs_len = 3*blks; } DPRINTF(VOLUMES, ("Got VRS of %d sectors long\n", vrs_len)); /* * location of iso9660 vrs is defined as first sector AFTER 32kb, * minimum ISO `sector size' 2048 */ sector_size = ump->discinfo.sector_size; iso9660_vrs = ((32*1024 + sector_size - 1) / sector_size) + write_track_start; /* write out 32 kb */ blank = malloc(sector_size, M_TEMP, M_WAITOK); memset(blank, 0, sector_size); error = 0; for (sector = write_track_start; sector < iso9660_vrs; sector ++) { error = udf_write_phys_sectors(ump, UDF_C_ABSOLUTE, blank, sector, 1); if (error) break; } if (!error) { /* write out our ISO VRS */ KASSERT(sector == iso9660_vrs); error = udf_write_phys_sectors(ump, UDF_C_ABSOLUTE, buffer, sector, vrs_len); sector += vrs_len; } if (!error) { /* fill upto the first anchor at S+256 */ for (; sector < write_track_start+256; sector++) { error = udf_write_phys_sectors(ump, UDF_C_ABSOLUTE, blank, sector, 1); if (error) break; } } if (!error) { /* write out anchor; write at ABSOLUTE place! */ error = udf_write_phys_dscr_sync(ump, NULL, UDF_C_ABSOLUTE, (union dscrptr *) ump->anchors[0], sector, sector); if (error) printf("writeout of anchor failed!\n"); } free(blank, M_TEMP); free(buffer, M_TEMP); if (error) printf("udf_open_session: error writing iso vrs! : " "leaving disc in compromised state!\n"); /* synchronise device caches */ (void) udf_synchronise_caches(ump); return error; } int udf_open_logvol(struct udf_mount *ump) { int logvol_integrity; int error; /* already/still open? */ logvol_integrity = udf_rw32(ump->logvol_integrity->integrity_type); if (logvol_integrity == UDF_INTEGRITY_OPEN) return 0; /* can we open it ? */ if (ump->vfs_mountp->mnt_flag & MNT_RDONLY) return EROFS; /* setup write parameters */ DPRINTF(VOLUMES, ("Setting up write parameters\n")); if ((error = udf_setup_writeparams(ump)) != 0) return error; /* determine data and metadata tracks (most likely same) */ error = udf_search_writing_tracks(ump); if (error) { /* most likely lack of space */ printf("udf_open_logvol: error searching writing tracks\n"); return EROFS; } /* writeout/update lvint on disc or only in memory */ DPRINTF(VOLUMES, ("Opening logical volume\n")); if (ump->lvopen & UDF_OPEN_SESSION) { /* TODO optional track reservation opening */ error = udf_validate_session_start(ump); if (error) return error; /* determine data and metadata tracks again */ error = udf_search_writing_tracks(ump); } /* mark it open */ ump->logvol_integrity->integrity_type = udf_rw32(UDF_INTEGRITY_OPEN); /* do we need to write it out? */ if (ump->lvopen & UDF_WRITE_LVINT) { error = udf_writeout_lvint(ump, ump->lvopen); /* if we couldn't write it mark it closed again */ if (error) { ump->logvol_integrity->integrity_type = udf_rw32(UDF_INTEGRITY_CLOSED); return error; } } return 0; } int udf_close_logvol(struct udf_mount *ump, int mntflags) { struct vnode *devvp = ump->devvp; struct mmc_op mmc_op; int logvol_integrity; int error = 0, error1 = 0, error2 = 0; int tracknr; int nvats, n, nok; /* already/still closed? */ logvol_integrity = udf_rw32(ump->logvol_integrity->integrity_type); if (logvol_integrity == UDF_INTEGRITY_CLOSED) return 0; /* writeout/update lvint or write out VAT */ DPRINTF(VOLUMES, ("udf_close_logvol: closing logical volume\n")); #ifdef DIAGNOSTIC if (ump->lvclose & UDF_CLOSE_SESSION) KASSERT(ump->lvclose & UDF_WRITE_VAT); #endif if (ump->lvclose & UDF_WRITE_VAT) { DPRINTF(VOLUMES, ("lvclose & UDF_WRITE_VAT\n")); /* write out the VAT data and all its descriptors */ DPRINTF(VOLUMES, ("writeout vat_node\n")); udf_writeout_vat(ump); (void) vflushbuf(ump->vat_node->vnode, FSYNC_WAIT); (void) VOP_FSYNC(ump->vat_node->vnode, FSCRED, FSYNC_WAIT, 0, 0); if (ump->lvclose & UDF_CLOSE_SESSION) { DPRINTF(VOLUMES, ("udf_close_logvol: closing session " "as requested\n")); } /* at least two DVD packets and 3 CD-R packets */ nvats = 32; #if notyet /* * TODO calculate the available space and if the disc is * allmost full, write out till end-256-1 with banks, write * AVDP and fill up with VATs, then close session and close * disc. */ if (ump->lvclose & UDF_FINALISE_DISC) { error = udf_write_phys_dscr_sync(ump, NULL, UDF_C_FLOAT_DSCR, (union dscrptr *) ump->anchors[0], 0, 0); if (error) printf("writeout of anchor failed!\n"); /* pad space with VAT ICBs */ nvats = 256; } #endif /* write out a number of VAT nodes */ nok = 0; for (n = 0; n < nvats; n++) { /* will now only write last FE/EFE */ ump->vat_node->i_flags |= IN_MODIFIED; error = VOP_FSYNC(ump->vat_node->vnode, FSCRED, FSYNC_WAIT, 0, 0); if (!error) nok++; } if (nok < 14) { /* arbitrary; but at least one or two CD frames */ printf("writeout of at least 14 VATs failed\n"); return error; } } /* NOTE the disc is in a (minimal) valid state now; no erroring out */ /* finish closing of session */ if (ump->lvclose & UDF_CLOSE_SESSION) { error = udf_validate_session_start(ump); if (error) return error; (void) udf_synchronise_caches(ump); /* close all associated tracks */ tracknr = ump->discinfo.first_track_last_session; error = 0; while (tracknr <= ump->discinfo.last_track_last_session) { DPRINTF(VOLUMES, ("\tclosing possible open " "track %d\n", tracknr)); memset(&mmc_op, 0, sizeof(mmc_op)); mmc_op.operation = MMC_OP_CLOSETRACK; mmc_op.mmc_profile = ump->discinfo.mmc_profile; mmc_op.tracknr = tracknr; error = VOP_IOCTL(devvp, MMCOP, &mmc_op, FKIOCTL, NOCRED); if (error) printf("udf_close_logvol: closing of " "track %d failed\n", tracknr); tracknr ++; } if (!error) { DPRINTF(VOLUMES, ("closing session\n")); memset(&mmc_op, 0, sizeof(mmc_op)); mmc_op.operation = MMC_OP_CLOSESESSION; mmc_op.mmc_profile = ump->discinfo.mmc_profile; mmc_op.sessionnr = ump->discinfo.num_sessions; error = VOP_IOCTL(devvp, MMCOP, &mmc_op, FKIOCTL, NOCRED); if (error) printf("udf_close_logvol: closing of session" "failed\n"); } if (!error) ump->lvopen |= UDF_OPEN_SESSION; if (error) { printf("udf_close_logvol: leaving disc as it is\n"); ump->lvclose &= ~UDF_FINALISE_DISC; } } if (ump->lvclose & UDF_FINALISE_DISC) { memset(&mmc_op, 0, sizeof(mmc_op)); mmc_op.operation = MMC_OP_FINALISEDISC; mmc_op.mmc_profile = ump->discinfo.mmc_profile; mmc_op.sessionnr = ump->discinfo.num_sessions; error = VOP_IOCTL(devvp, MMCOP, &mmc_op, FKIOCTL, NOCRED); if (error) printf("udf_close_logvol: finalising disc" "failed\n"); } /* write out partition bitmaps if requested */ if (ump->lvclose & UDF_WRITE_PART_BITMAPS) { /* sync writeout metadata spacetable if existing */ error1 = udf_write_metadata_partition_spacetable(ump, true); if (error1) printf( "udf_close_logvol: writeout of metadata space " "bitmap failed\n"); /* sync writeout partition spacetables */ error2 = udf_write_physical_partition_spacetables(ump, true); if (error2) printf( "udf_close_logvol: writeout of space tables " "failed\n"); if (error1 || error2) return (error1 | error2); ump->lvclose &= ~UDF_WRITE_PART_BITMAPS; } /* write out metadata partition nodes if requested */ if (ump->lvclose & UDF_WRITE_METAPART_NODES) { /* sync writeout metadata descriptor node */ error1 = udf_writeout_node(ump->metadata_node, FSYNC_WAIT); if (error1) printf( "udf_close_logvol: writeout of metadata partition " "node failed\n"); /* duplicate metadata partition descriptor if needed */ udf_synchronise_metadatamirror_node(ump); /* sync writeout metadatamirror descriptor node */ error2 = udf_writeout_node(ump->metadatamirror_node, FSYNC_WAIT); if (error2) printf( "udf_close_logvol: writeout of metadata partition " "mirror node failed\n"); if (error1 || error2) return (error1 | error2); ump->lvclose &= ~UDF_WRITE_METAPART_NODES; } /* mark it closed */ ump->logvol_integrity->integrity_type = udf_rw32(UDF_INTEGRITY_CLOSED); /* do we need to write out the logical volume integrity? */ if (ump->lvclose & UDF_WRITE_LVINT) error = udf_writeout_lvint(ump, ump->lvopen); if (error) { /* HELP now what? mark it open again for now */ ump->logvol_integrity->integrity_type = udf_rw32(UDF_INTEGRITY_OPEN); return error; } (void) udf_synchronise_caches(ump); return 0; } /* --------------------------------------------------------------------- */ /* * Genfs interfacing * * static const struct genfs_ops udf_genfsops = { * .gop_size = genfs_size, * size of transfers * .gop_alloc = udf_gop_alloc, * allocate len bytes at offset * .gop_write = genfs_gop_write, * putpages interface code * .gop_markupdate = udf_gop_markupdate, * set update/modify flags etc. * } */ /* * Genfs interface. These four functions are the only ones defined though not * documented... great.... */ /* * Called for allocating an extent of the file either by VOP_WRITE() or by * genfs filling up gaps. */ static int udf_gop_alloc(struct vnode *vp, off_t off, off_t len, int flags, kauth_cred_t cred) { struct udf_node *udf_node = VTOI(vp); struct udf_mount *ump = udf_node->ump; uint64_t lb_start, lb_end; uint32_t lb_size, num_lb; int udf_c_type, vpart_num, can_fail; int error; DPRINTF(ALLOC, ("udf_gop_alloc called for offset %"PRIu64" for %"PRIu64" bytes, %s\n", off, len, flags? "SYNC":"NONE")); /* * request the pages of our vnode and see how many pages will need to * be allocated and reserve that space */ lb_size = udf_rw32(udf_node->ump->logical_vol->lb_size); lb_start = off / lb_size; lb_end = (off + len + lb_size -1) / lb_size; num_lb = lb_end - lb_start; udf_c_type = udf_get_c_type(udf_node); vpart_num = udf_get_record_vpart(ump, udf_c_type); /* all requests can fail */ can_fail = true; /* fid's (directories) can't fail */ if (udf_c_type == UDF_C_FIDS) can_fail = false; /* system files can't fail */ if (vp->v_vflag & VV_SYSTEM) can_fail = false; error = udf_reserve_space(ump, udf_node, udf_c_type, vpart_num, num_lb, can_fail); DPRINTF(ALLOC, ("\tlb_start %"PRIu64", lb_end %"PRIu64", num_lb %d\n", lb_start, lb_end, num_lb)); return error; } /* * callback from genfs to update our flags */ static void udf_gop_markupdate(struct vnode *vp, int flags) { struct udf_node *udf_node = VTOI(vp); u_long mask = 0; if ((flags & GOP_UPDATE_ACCESSED) != 0) { mask = IN_ACCESS; } if ((flags & GOP_UPDATE_MODIFIED) != 0) { if (vp->v_type == VREG) { mask |= IN_CHANGE | IN_UPDATE; } else { mask |= IN_MODIFY; } } if (mask) { udf_node->i_flags |= mask; } } static const struct genfs_ops udf_genfsops = { .gop_size = genfs_size, .gop_alloc = udf_gop_alloc, .gop_write = genfs_gop_write_rwmap, .gop_markupdate = udf_gop_markupdate, }; /* --------------------------------------------------------------------- */ int udf_write_terminator(struct udf_mount *ump, uint32_t sector) { union dscrptr *dscr; int error; dscr = malloc(ump->discinfo.sector_size, M_TEMP, M_WAITOK|M_ZERO); udf_inittag(ump, &dscr->tag, TAGID_TERM, sector); /* CRC length for an anchor is 512 - tag length; defined in Ecma 167 */ dscr->tag.desc_crc_len = udf_rw16(512-UDF_DESC_TAG_LENGTH); (void) udf_validate_tag_and_crc_sums(dscr); error = udf_write_phys_dscr_sync(ump, NULL, UDF_C_DSCR, dscr, sector, sector); free(dscr, M_TEMP); return error; } /* --------------------------------------------------------------------- */ /* UDF<->unix converters */ /* --------------------------------------------------------------------- */ static mode_t udf_perm_to_unix_mode(uint32_t perm) { mode_t mode; mode = ((perm & UDF_FENTRY_PERM_USER_MASK) ); mode |= ((perm & UDF_FENTRY_PERM_GRP_MASK ) >> 2); mode |= ((perm & UDF_FENTRY_PERM_OWNER_MASK) >> 4); return mode; } /* --------------------------------------------------------------------- */ static uint32_t unix_mode_to_udf_perm(mode_t mode) { uint32_t perm; perm = ((mode & S_IRWXO) ); perm |= ((mode & S_IRWXG) << 2); perm |= ((mode & S_IRWXU) << 4); perm |= ((mode & S_IWOTH) << 3); perm |= ((mode & S_IWGRP) << 5); perm |= ((mode & S_IWUSR) << 7); return perm; } /* --------------------------------------------------------------------- */ static uint32_t udf_icb_to_unix_filetype(uint32_t icbftype) { switch (icbftype) { case UDF_ICB_FILETYPE_DIRECTORY : case UDF_ICB_FILETYPE_STREAMDIR : return S_IFDIR; case UDF_ICB_FILETYPE_FIFO : return S_IFIFO; case UDF_ICB_FILETYPE_CHARDEVICE : return S_IFCHR; case UDF_ICB_FILETYPE_BLOCKDEVICE : return S_IFBLK; case UDF_ICB_FILETYPE_RANDOMACCESS : case UDF_ICB_FILETYPE_REALTIME : return S_IFREG; case UDF_ICB_FILETYPE_SYMLINK : return S_IFLNK; case UDF_ICB_FILETYPE_SOCKET : return S_IFSOCK; } /* no idea what this is */ return 0; } /* --------------------------------------------------------------------- */ void udf_to_unix_name(char *result, int result_len, char *id, int len, struct charspec *chsp) { uint16_t *raw_name, *unix_name; uint16_t *inchp, ch; uint8_t *outchp; const char *osta_id = "OSTA Compressed Unicode"; int ucode_chars, nice_uchars, is_osta_typ0, nout; raw_name = malloc(2048 * sizeof(uint16_t), M_UDFTEMP, M_WAITOK); unix_name = raw_name + 1024; /* split space in half */ assert(sizeof(char) == sizeof(uint8_t)); outchp = (uint8_t *) result; is_osta_typ0 = (chsp->type == 0); is_osta_typ0 &= (strcmp((char *) chsp->inf, osta_id) == 0); if (is_osta_typ0) { /* TODO clean up */ *raw_name = *unix_name = 0; ucode_chars = udf_UncompressUnicode(len, (uint8_t *) id, raw_name); ucode_chars = MIN(ucode_chars, UnicodeLength((unicode_t *) raw_name)); nice_uchars = UDFTransName(unix_name, raw_name, ucode_chars); /* output UTF8 */ for (inchp = unix_name; nice_uchars>0; inchp++, nice_uchars--) { ch = *inchp; nout = wput_utf8(outchp, result_len, ch); outchp += nout; result_len -= nout; if (!ch) break; } *outchp++ = 0; } else { /* assume 8bit char length byte latin-1 */ assert(*id == 8); assert(strlen((char *) (id+1)) <= NAME_MAX); strncpy((char *) result, (char *) (id+1), strlen((char *) (id+1))); } free(raw_name, M_UDFTEMP); } /* --------------------------------------------------------------------- */ void unix_to_udf_name(char *result, uint8_t *result_len, char const *name, int name_len, struct charspec *chsp) { uint16_t *raw_name; uint16_t *outchp; const char *inchp; const char *osta_id = "OSTA Compressed Unicode"; int udf_chars, is_osta_typ0, bits; size_t cnt; /* allocate temporary unicode-16 buffer */ raw_name = malloc(1024, M_UDFTEMP, M_WAITOK); /* convert utf8 to unicode-16 */ *raw_name = 0; inchp = name; outchp = raw_name; bits = 8; for (cnt = name_len, udf_chars = 0; cnt;) { *outchp = wget_utf8(&inchp, &cnt); if (*outchp > 0xff) bits=16; outchp++; udf_chars++; } /* null terminate just in case */ *outchp++ = 0; is_osta_typ0 = (chsp->type == 0); is_osta_typ0 &= (strcmp((char *) chsp->inf, osta_id) == 0); if (is_osta_typ0) { udf_chars = udf_CompressUnicode(udf_chars, bits, (unicode_t *) raw_name, (byte *) result); } else { printf("unix to udf name: no CHSP0 ?\n"); /* XXX assume 8bit char length byte latin-1 */ *result++ = 8; udf_chars = 1; strncpy(result, name + 1, name_len); udf_chars += name_len; } *result_len = udf_chars; free(raw_name, M_UDFTEMP); } /* --------------------------------------------------------------------- */ void udf_timestamp_to_timespec(struct udf_mount *ump, struct timestamp *timestamp, struct timespec *timespec) { struct clock_ymdhms ymdhms; uint32_t usecs, secs, nsecs; uint16_t tz; /* fill in ymdhms structure from timestamp */ memset(&ymdhms, 0, sizeof(ymdhms)); ymdhms.dt_year = udf_rw16(timestamp->year); ymdhms.dt_mon = timestamp->month; ymdhms.dt_day = timestamp->day; ymdhms.dt_wday = 0; /* ? */ ymdhms.dt_hour = timestamp->hour; ymdhms.dt_min = timestamp->minute; ymdhms.dt_sec = timestamp->second; secs = clock_ymdhms_to_secs(&ymdhms); usecs = timestamp->usec + 100*timestamp->hund_usec + 10000*timestamp->centisec; nsecs = usecs * 1000; /* * Calculate the time zone. The timezone is 12 bit signed 2's * compliment, so we gotta do some extra magic to handle it right. */ tz = udf_rw16(timestamp->type_tz); tz &= 0x0fff; /* only lower 12 bits are significant */ if (tz & 0x0800) /* sign extention */ tz |= 0xf000; /* TODO check timezone conversion */ /* check if we are specified a timezone to convert */ if (udf_rw16(timestamp->type_tz) & 0x1000) { if ((int16_t) tz != -2047) secs -= (int16_t) tz * 60; } else { secs -= ump->mount_args.gmtoff; } timespec->tv_sec = secs; timespec->tv_nsec = nsecs; } void udf_timespec_to_timestamp(struct timespec *timespec, struct timestamp *timestamp) { struct clock_ymdhms ymdhms; uint32_t husec, usec, csec; (void) clock_secs_to_ymdhms(timespec->tv_sec, &ymdhms); usec = timespec->tv_nsec / 1000; husec = usec / 100; usec -= husec * 100; /* only 0-99 in usec */ csec = husec / 100; /* only 0-99 in csec */ husec -= csec * 100; /* only 0-99 in husec */ /* set method 1 for CUT/GMT */ timestamp->type_tz = udf_rw16((1<<12) + 0); timestamp->year = udf_rw16(ymdhms.dt_year); timestamp->month = ymdhms.dt_mon; timestamp->day = ymdhms.dt_day; timestamp->hour = ymdhms.dt_hour; timestamp->minute = ymdhms.dt_min; timestamp->second = ymdhms.dt_sec; timestamp->centisec = csec; timestamp->hund_usec = husec; timestamp->usec = usec; } /* --------------------------------------------------------------------- */ /* * Attribute and filetypes converters with get/set pairs */ uint32_t udf_getaccessmode(struct udf_node *udf_node) { struct file_entry *fe = udf_node->fe; struct extfile_entry *efe = udf_node->efe; uint32_t udf_perm, icbftype; uint32_t mode, ftype; uint16_t icbflags; UDF_LOCK_NODE(udf_node, 0); if (fe) { udf_perm = udf_rw32(fe->perm); icbftype = fe->icbtag.file_type; icbflags = udf_rw16(fe->icbtag.flags); } else { assert(udf_node->efe); udf_perm = udf_rw32(efe->perm); icbftype = efe->icbtag.file_type; icbflags = udf_rw16(efe->icbtag.flags); } mode = udf_perm_to_unix_mode(udf_perm); ftype = udf_icb_to_unix_filetype(icbftype); /* set suid, sgid, sticky from flags in fe/efe */ if (icbflags & UDF_ICB_TAG_FLAGS_SETUID) mode |= S_ISUID; if (icbflags & UDF_ICB_TAG_FLAGS_SETGID) mode |= S_ISGID; if (icbflags & UDF_ICB_TAG_FLAGS_STICKY) mode |= S_ISVTX; UDF_UNLOCK_NODE(udf_node, 0); return mode | ftype; } void udf_setaccessmode(struct udf_node *udf_node, mode_t mode) { struct file_entry *fe = udf_node->fe; struct extfile_entry *efe = udf_node->efe; uint32_t udf_perm; uint16_t icbflags; UDF_LOCK_NODE(udf_node, 0); udf_perm = unix_mode_to_udf_perm(mode & ALLPERMS); if (fe) { icbflags = udf_rw16(fe->icbtag.flags); } else { icbflags = udf_rw16(efe->icbtag.flags); } icbflags &= ~UDF_ICB_TAG_FLAGS_SETUID; icbflags &= ~UDF_ICB_TAG_FLAGS_SETGID; icbflags &= ~UDF_ICB_TAG_FLAGS_STICKY; if (mode & S_ISUID) icbflags |= UDF_ICB_TAG_FLAGS_SETUID; if (mode & S_ISGID) icbflags |= UDF_ICB_TAG_FLAGS_SETGID; if (mode & S_ISVTX) icbflags |= UDF_ICB_TAG_FLAGS_STICKY; if (fe) { fe->perm = udf_rw32(udf_perm); fe->icbtag.flags = udf_rw16(icbflags); } else { efe->perm = udf_rw32(udf_perm); efe->icbtag.flags = udf_rw16(icbflags); } UDF_UNLOCK_NODE(udf_node, 0); } void udf_getownership(struct udf_node *udf_node, uid_t *uidp, gid_t *gidp) { struct udf_mount *ump = udf_node->ump; struct file_entry *fe = udf_node->fe; struct extfile_entry *efe = udf_node->efe; uid_t uid; gid_t gid; UDF_LOCK_NODE(udf_node, 0); if (fe) { uid = (uid_t)udf_rw32(fe->uid); gid = (gid_t)udf_rw32(fe->gid); } else { assert(udf_node->efe); uid = (uid_t)udf_rw32(efe->uid); gid = (gid_t)udf_rw32(efe->gid); } /* do the uid/gid translation game */ if (uid == (uid_t) -1) uid = ump->mount_args.anon_uid; if (gid == (gid_t) -1) gid = ump->mount_args.anon_gid; *uidp = uid; *gidp = gid; UDF_UNLOCK_NODE(udf_node, 0); } void udf_setownership(struct udf_node *udf_node, uid_t uid, gid_t gid) { struct udf_mount *ump = udf_node->ump; struct file_entry *fe = udf_node->fe; struct extfile_entry *efe = udf_node->efe; uid_t nobody_uid; gid_t nobody_gid; UDF_LOCK_NODE(udf_node, 0); /* do the uid/gid translation game */ nobody_uid = ump->mount_args.nobody_uid; nobody_gid = ump->mount_args.nobody_gid; if (uid == nobody_uid) uid = (uid_t) -1; if (gid == nobody_gid) gid = (gid_t) -1; if (fe) { fe->uid = udf_rw32((uint32_t) uid); fe->gid = udf_rw32((uint32_t) gid); } else { efe->uid = udf_rw32((uint32_t) uid); efe->gid = udf_rw32((uint32_t) gid); } UDF_UNLOCK_NODE(udf_node, 0); } /* --------------------------------------------------------------------- */ int udf_dirhash_fill(struct udf_node *dir_node) { struct vnode *dvp = dir_node->vnode; struct dirhash *dirh; struct file_entry *fe = dir_node->fe; struct extfile_entry *efe = dir_node->efe; struct fileid_desc *fid; struct dirent *dirent; uint64_t file_size, pre_diroffset, diroffset; uint32_t lb_size; int error; /* make sure we have a dirhash to work on */ dirh = dir_node->dir_hash; KASSERT(dirh); KASSERT(dirh->refcnt > 0); if (dirh->flags & DIRH_BROKEN) return EIO; if (dirh->flags & DIRH_COMPLETE) return 0; /* make sure we have a clean dirhash to add to */ dirhash_purge_entries(dirh); /* get directory filesize */ if (fe) { file_size = udf_rw64(fe->inf_len); } else { assert(efe); file_size = udf_rw64(efe->inf_len); } /* allocate temporary space for fid */ lb_size = udf_rw32(dir_node->ump->logical_vol->lb_size); fid = malloc(lb_size, M_UDFTEMP, M_WAITOK); /* allocate temporary space for dirent */ dirent = malloc(sizeof(struct dirent), M_UDFTEMP, M_WAITOK); error = 0; diroffset = 0; while (diroffset < file_size) { /* transfer a new fid/dirent */ pre_diroffset = diroffset; error = udf_read_fid_stream(dvp, &diroffset, fid, dirent); if (error) { /* TODO what to do? continue but not add? */ dirh->flags |= DIRH_BROKEN; dirhash_purge_entries(dirh); break; } if ((fid->file_char & UDF_FILE_CHAR_DEL)) { /* register deleted extent for reuse */ dirhash_enter_freed(dirh, pre_diroffset, udf_fidsize(fid)); } else { /* append to the dirhash */ dirhash_enter(dirh, dirent, pre_diroffset, udf_fidsize(fid), 0); } } dirh->flags |= DIRH_COMPLETE; free(fid, M_UDFTEMP); free(dirent, M_UDFTEMP); return error; } /* --------------------------------------------------------------------- */ /* * Directory read and manipulation functions. * */ int udf_lookup_name_in_dir(struct vnode *vp, const char *name, int namelen, struct long_ad *icb_loc, int *found) { struct udf_node *dir_node = VTOI(vp); struct dirhash *dirh; struct dirhash_entry *dirh_ep; struct fileid_desc *fid; struct dirent *dirent; uint64_t diroffset; uint32_t lb_size; int hit, error; /* set default return */ *found = 0; /* get our dirhash and make sure its read in */ dirhash_get(&dir_node->dir_hash); error = udf_dirhash_fill(dir_node); if (error) { dirhash_put(dir_node->dir_hash); return error; } dirh = dir_node->dir_hash; /* allocate temporary space for fid */ lb_size = udf_rw32(dir_node->ump->logical_vol->lb_size); fid = malloc(lb_size, M_UDFTEMP, M_WAITOK); dirent = malloc(sizeof(struct dirent), M_UDFTEMP, M_WAITOK); DPRINTF(DIRHASH, ("dirhash_lookup looking for `%*.*s`\n", namelen, namelen, name)); /* search our dirhash hits */ memset(icb_loc, 0, sizeof(*icb_loc)); dirh_ep = NULL; for (;;) { hit = dirhash_lookup(dirh, name, namelen, &dirh_ep); /* if no hit, abort the search */ if (!hit) break; /* check this hit */ diroffset = dirh_ep->offset; /* transfer a new fid/dirent */ error = udf_read_fid_stream(vp, &diroffset, fid, dirent); if (error) break; DPRINTF(DIRHASH, ("dirhash_lookup\tchecking `%*.*s`\n", dirent->d_namlen, dirent->d_namlen, dirent->d_name)); /* see if its our entry */ #ifdef DIAGNOSTIC if (dirent->d_namlen != namelen) { printf("WARNING: dirhash_lookup() returned wrong " "d_namelen: %d and ought to be %d\n", dirent->d_namlen, namelen); printf("\tlooked for `%s' and got `%s'\n", name, dirent->d_name); } #endif if (strncmp(dirent->d_name, name, namelen) == 0) { *found = 1; *icb_loc = fid->icb; break; } } free(fid, M_UDFTEMP); free(dirent, M_UDFTEMP); dirhash_put(dir_node->dir_hash); return error; } /* --------------------------------------------------------------------- */ static int udf_create_new_fe(struct udf_mount *ump, struct file_entry *fe, int file_type, struct long_ad *node_icb, struct long_ad *parent_icb, uint64_t parent_unique_id) { struct timespec now; struct icb_tag *icb; struct filetimes_extattr_entry *ft_extattr; uint64_t unique_id; uint32_t fidsize, lb_num; uint8_t *bpos; int crclen, attrlen; lb_num = udf_rw32(node_icb->loc.lb_num); udf_inittag(ump, &fe->tag, TAGID_FENTRY, lb_num); icb = &fe->icbtag; /* * Always use strategy type 4 unless on WORM wich we don't support * (yet). Fill in defaults and set for internal allocation of data. */ icb->strat_type = udf_rw16(4); icb->max_num_entries = udf_rw16(1); icb->file_type = file_type; /* 8 bit */ icb->flags = udf_rw16(UDF_ICB_INTERN_ALLOC); fe->perm = udf_rw32(0x7fff); /* all is allowed */ fe->link_cnt = udf_rw16(0); /* explicit setting */ fe->ckpoint = udf_rw32(1); /* user supplied file version */ vfs_timestamp(&now); udf_timespec_to_timestamp(&now, &fe->atime); udf_timespec_to_timestamp(&now, &fe->attrtime); udf_timespec_to_timestamp(&now, &fe->mtime); udf_set_regid(&fe->imp_id, IMPL_NAME); udf_add_impl_regid(ump, &fe->imp_id); unique_id = udf_advance_uniqueid(ump); fe->unique_id = udf_rw64(unique_id); fe->l_ea = udf_rw32(0); /* create extended attribute to record our creation time */ attrlen = UDF_FILETIMES_ATTR_SIZE(1); ft_extattr = malloc(attrlen, M_UDFTEMP, M_WAITOK); memset(ft_extattr, 0, attrlen); ft_extattr->hdr.type = udf_rw32(UDF_FILETIMES_ATTR_NO); ft_extattr->hdr.subtype = 1; /* [4/48.10.5] */ ft_extattr->hdr.a_l = udf_rw32(UDF_FILETIMES_ATTR_SIZE(1)); ft_extattr->d_l = udf_rw32(UDF_TIMESTAMP_SIZE); /* one item */ ft_extattr->existence = UDF_FILETIMES_FILE_CREATION; udf_timespec_to_timestamp(&now, &ft_extattr->times[0]); udf_extattr_insert_internal(ump, (union dscrptr *) fe, (struct extattr_entry *) ft_extattr); free(ft_extattr, M_UDFTEMP); /* if its a directory, create '..' */ bpos = (uint8_t *) fe->data + udf_rw32(fe->l_ea); fidsize = 0; if (file_type == UDF_ICB_FILETYPE_DIRECTORY) { fidsize = udf_create_parentfid(ump, (struct fileid_desc *) bpos, parent_icb, parent_unique_id); } /* record fidlength information */ fe->inf_len = udf_rw64(fidsize); fe->l_ad = udf_rw32(fidsize); fe->logblks_rec = udf_rw64(0); /* intern */ crclen = sizeof(struct file_entry) - 1 - UDF_DESC_TAG_LENGTH; crclen += udf_rw32(fe->l_ea) + fidsize; fe->tag.desc_crc_len = udf_rw16(crclen); (void) udf_validate_tag_and_crc_sums((union dscrptr *) fe); return fidsize; } /* --------------------------------------------------------------------- */ static int udf_create_new_efe(struct udf_mount *ump, struct extfile_entry *efe, int file_type, struct long_ad *node_icb, struct long_ad *parent_icb, uint64_t parent_unique_id) { struct timespec now; struct icb_tag *icb; uint64_t unique_id; uint32_t fidsize, lb_num; uint8_t *bpos; int crclen; lb_num = udf_rw32(node_icb->loc.lb_num); udf_inittag(ump, &efe->tag, TAGID_EXTFENTRY, lb_num); icb = &efe->icbtag; /* * Always use strategy type 4 unless on WORM wich we don't support * (yet). Fill in defaults and set for internal allocation of data. */ icb->strat_type = udf_rw16(4); icb->max_num_entries = udf_rw16(1); icb->file_type = file_type; /* 8 bit */ icb->flags = udf_rw16(UDF_ICB_INTERN_ALLOC); efe->perm = udf_rw32(0x7fff); /* all is allowed */ efe->link_cnt = udf_rw16(0); /* explicit setting */ efe->ckpoint = udf_rw32(1); /* user supplied file version */ vfs_timestamp(&now); udf_timespec_to_timestamp(&now, &efe->ctime); udf_timespec_to_timestamp(&now, &efe->atime); udf_timespec_to_timestamp(&now, &efe->attrtime); udf_timespec_to_timestamp(&now, &efe->mtime); udf_set_regid(&efe->imp_id, IMPL_NAME); udf_add_impl_regid(ump, &efe->imp_id); unique_id = udf_advance_uniqueid(ump); efe->unique_id = udf_rw64(unique_id); efe->l_ea = udf_rw32(0); /* if its a directory, create '..' */ bpos = (uint8_t *) efe->data + udf_rw32(efe->l_ea); fidsize = 0; if (file_type == UDF_ICB_FILETYPE_DIRECTORY) { fidsize = udf_create_parentfid(ump, (struct fileid_desc *) bpos, parent_icb, parent_unique_id); } /* record fidlength information */ efe->obj_size = udf_rw64(fidsize); efe->inf_len = udf_rw64(fidsize); efe->l_ad = udf_rw32(fidsize); efe->logblks_rec = udf_rw64(0); /* intern */ crclen = sizeof(struct extfile_entry) - 1 - UDF_DESC_TAG_LENGTH; crclen += udf_rw32(efe->l_ea) + fidsize; efe->tag.desc_crc_len = udf_rw16(crclen); (void) udf_validate_tag_and_crc_sums((union dscrptr *) efe); return fidsize; } /* --------------------------------------------------------------------- */ int udf_dir_detach(struct udf_mount *ump, struct udf_node *dir_node, struct udf_node *udf_node, struct componentname *cnp) { struct vnode *dvp = dir_node->vnode; struct dirhash *dirh; struct dirhash_entry *dirh_ep; struct file_entry *fe = dir_node->fe; struct fileid_desc *fid; struct dirent *dirent; uint64_t diroffset; uint32_t lb_size, fidsize; int found, error; char const *name = cnp->cn_nameptr; int namelen = cnp->cn_namelen; int hit, refcnt; /* get our dirhash and make sure its read in */ dirhash_get(&dir_node->dir_hash); error = udf_dirhash_fill(dir_node); if (error) { dirhash_put(dir_node->dir_hash); return error; } dirh = dir_node->dir_hash; /* get directory filesize */ if (!fe) { assert(dir_node->efe); } /* allocate temporary space for fid */ lb_size = udf_rw32(dir_node->ump->logical_vol->lb_size); fid = malloc(lb_size, M_UDFTEMP, M_WAITOK); dirent = malloc(sizeof(struct dirent), M_UDFTEMP, M_WAITOK); /* search our dirhash hits */ found = 0; dirh_ep = NULL; for (;;) { hit = dirhash_lookup(dirh, name, namelen, &dirh_ep); /* if no hit, abort the search */ if (!hit) break; /* check this hit */ diroffset = dirh_ep->offset; /* transfer a new fid/dirent */ error = udf_read_fid_stream(dvp, &diroffset, fid, dirent); if (error) break; /* see if its our entry */ KASSERT(dirent->d_namlen == namelen); if (strncmp(dirent->d_name, name, namelen) == 0) { found = 1; break; } } if (!found) error = ENOENT; if (error) goto error_out; /* mark deleted */ fid->file_char |= UDF_FILE_CHAR_DEL; #ifdef UDF_COMPLETE_DELETE memset(&fid->icb, 0, sizeof(fid->icb)); #endif (void) udf_validate_tag_and_crc_sums((union dscrptr *) fid); /* get size of fid and compensate for the read_fid_stream advance */ fidsize = udf_fidsize(fid); diroffset -= fidsize; /* write out */ error = vn_rdwr(UIO_WRITE, dir_node->vnode, fid, fidsize, diroffset, UIO_SYSSPACE, IO_ALTSEMANTICS | IO_NODELOCKED, FSCRED, NULL, NULL); if (error) goto error_out; /* get reference count of attached node */ if (udf_node->fe) { refcnt = udf_rw16(udf_node->fe->link_cnt); } else { KASSERT(udf_node->efe); refcnt = udf_rw16(udf_node->efe->link_cnt); } #ifdef UDF_COMPLETE_DELETE /* substract reference counter in attached node */ refcnt -= 1; if (udf_node->fe) { udf_node->fe->link_cnt = udf_rw16(refcnt); } else { udf_node->efe->link_cnt = udf_rw16(refcnt); } /* prevent writeout when refcnt == 0 */ if (refcnt == 0) udf_node->i_flags |= IN_DELETED; if (fid->file_char & UDF_FILE_CHAR_DIR) { int drefcnt; /* substract reference counter in directory node */ /* note subtract 2 (?) for its was also backreferenced */ if (dir_node->fe) { drefcnt = udf_rw16(dir_node->fe->link_cnt); drefcnt -= 1; dir_node->fe->link_cnt = udf_rw16(drefcnt); } else { KASSERT(dir_node->efe); drefcnt = udf_rw16(dir_node->efe->link_cnt); drefcnt -= 1; dir_node->efe->link_cnt = udf_rw16(drefcnt); } } udf_node->i_flags |= IN_MODIFIED; dir_node->i_flags |= IN_MODIFIED; #endif /* if it is/was a hardlink adjust the file count */ if (refcnt > 0) udf_adjust_filecount(udf_node, -1); /* remove from the dirhash */ dirhash_remove(dirh, dirent, diroffset, udf_fidsize(fid)); error_out: free(fid, M_UDFTEMP); free(dirent, M_UDFTEMP); dirhash_put(dir_node->dir_hash); return error; } /* --------------------------------------------------------------------- */ int udf_dir_update_rootentry(struct udf_mount *ump, struct udf_node *dir_node, struct udf_node *new_parent_node) { struct vnode *dvp = dir_node->vnode; struct dirhash *dirh; struct dirhash_entry *dirh_ep; struct file_entry *fe; struct extfile_entry *efe; struct fileid_desc *fid; struct dirent *dirent; uint64_t diroffset; uint64_t new_parent_unique_id; uint32_t lb_size, fidsize; int found, error; char const *name = ".."; int namelen = 2; int hit; /* get our dirhash and make sure its read in */ dirhash_get(&dir_node->dir_hash); error = udf_dirhash_fill(dir_node); if (error) { dirhash_put(dir_node->dir_hash); return error; } dirh = dir_node->dir_hash; /* get new parent's unique ID */ fe = new_parent_node->fe; efe = new_parent_node->efe; if (fe) { new_parent_unique_id = udf_rw64(fe->unique_id); } else { assert(efe); new_parent_unique_id = udf_rw64(efe->unique_id); } /* get directory filesize */ fe = dir_node->fe; efe = dir_node->efe; if (!fe) { assert(efe); } /* allocate temporary space for fid */ lb_size = udf_rw32(dir_node->ump->logical_vol->lb_size); fid = malloc(lb_size, M_UDFTEMP, M_WAITOK); dirent = malloc(sizeof(struct dirent), M_UDFTEMP, M_WAITOK); /* * NOTE the standard does not dictate the FID entry '..' should be * first, though in practice it will most likely be. */ /* search our dirhash hits */ found = 0; dirh_ep = NULL; for (;;) { hit = dirhash_lookup(dirh, name, namelen, &dirh_ep); /* if no hit, abort the search */ if (!hit) break; /* check this hit */ diroffset = dirh_ep->offset; /* transfer a new fid/dirent */ error = udf_read_fid_stream(dvp, &diroffset, fid, dirent); if (error) break; /* see if its our entry */ KASSERT(dirent->d_namlen == namelen); if (strncmp(dirent->d_name, name, namelen) == 0) { found = 1; break; } } if (!found) error = ENOENT; if (error) goto error_out; /* update our ICB to the new parent, hit of lower 32 bits of uniqueid */ fid->icb = new_parent_node->write_loc; fid->icb.longad_uniqueid = udf_rw32(new_parent_unique_id); (void) udf_validate_tag_and_crc_sums((union dscrptr *) fid); /* get size of fid and compensate for the read_fid_stream advance */ fidsize = udf_fidsize(fid); diroffset -= fidsize; /* write out */ error = vn_rdwr(UIO_WRITE, dir_node->vnode, fid, fidsize, diroffset, UIO_SYSSPACE, IO_ALTSEMANTICS | IO_NODELOCKED, FSCRED, NULL, NULL); /* nothing to be done in the dirhash */ error_out: free(fid, M_UDFTEMP); free(dirent, M_UDFTEMP); dirhash_put(dir_node->dir_hash); return error; } /* --------------------------------------------------------------------- */ /* * We are not allowed to split the fid tag itself over an logical block so * check the space remaining in the logical block. * * We try to select the smallest candidate for recycling or when none is * found, append a new one at the end of the directory. */ int udf_dir_attach(struct udf_mount *ump, struct udf_node *dir_node, struct udf_node *udf_node, struct vattr *vap, struct componentname *cnp) { struct vnode *dvp = dir_node->vnode; struct dirhash *dirh; struct dirhash_entry *dirh_ep; struct fileid_desc *fid; struct icb_tag *icbtag; struct charspec osta_charspec; struct dirent dirent; uint64_t unique_id, dir_size; uint64_t fid_pos, end_fid_pos, chosen_fid_pos; uint32_t chosen_size, chosen_size_diff; int lb_size, lb_rest, fidsize, this_fidsize, size_diff; int file_char, refcnt, icbflags, addr_type, hit, error; /* get our dirhash and make sure its read in */ dirhash_get(&dir_node->dir_hash); error = udf_dirhash_fill(dir_node); if (error) { dirhash_put(dir_node->dir_hash); return error; } dirh = dir_node->dir_hash; /* get info */ lb_size = udf_rw32(ump->logical_vol->lb_size); udf_osta_charset(&osta_charspec); if (dir_node->fe) { dir_size = udf_rw64(dir_node->fe->inf_len); icbtag = &dir_node->fe->icbtag; } else { dir_size = udf_rw64(dir_node->efe->inf_len); icbtag = &dir_node->efe->icbtag; } icbflags = udf_rw16(icbtag->flags); addr_type = icbflags & UDF_ICB_TAG_FLAGS_ALLOC_MASK; if (udf_node->fe) { unique_id = udf_rw64(udf_node->fe->unique_id); refcnt = udf_rw16(udf_node->fe->link_cnt); } else { unique_id = udf_rw64(udf_node->efe->unique_id); refcnt = udf_rw16(udf_node->efe->link_cnt); } if (refcnt > 0) { unique_id = udf_advance_uniqueid(ump); udf_adjust_filecount(udf_node, 1); } /* determine file characteristics */ file_char = 0; /* visible non deleted file and not stream metadata */ if (vap->va_type == VDIR) file_char = UDF_FILE_CHAR_DIR; /* malloc scrap buffer */ fid = malloc(lb_size, M_TEMP, M_WAITOK|M_ZERO); /* calculate _minimum_ fid size */ unix_to_udf_name((char *) fid->data, &fid->l_fi, cnp->cn_nameptr, cnp->cn_namelen, &osta_charspec); fidsize = UDF_FID_SIZE + fid->l_fi; fidsize = (fidsize + 3) & ~3; /* multiple of 4 */ /* find position that will fit the FID */ chosen_fid_pos = dir_size; chosen_size = 0; chosen_size_diff = UINT_MAX; /* shut up gcc */ dirent.d_namlen = 0; /* search our dirhash hits */ error = 0; dirh_ep = NULL; for (;;) { hit = dirhash_lookup_freed(dirh, fidsize, &dirh_ep); /* if no hit, abort the search */ if (!hit) break; /* check this hit for size */ this_fidsize = dirh_ep->entry_size; /* check this hit */ fid_pos = dirh_ep->offset; end_fid_pos = fid_pos + this_fidsize; size_diff = this_fidsize - fidsize; lb_rest = lb_size - (end_fid_pos % lb_size); #ifndef UDF_COMPLETE_DELETE /* transfer a new fid/dirent */ error = udf_read_fid_stream(vp, &fid_pos, fid, dirent); if (error) goto error_out; /* only reuse entries that are wiped */ /* check if the len + loc are marked zero */ if (udf_rw32(fid->icb.len) != 0) continue; if (udf_rw32(fid->icb.loc.lb_num) != 0) continue; if (udf_rw16(fid->icb.loc.part_num) != 0) continue; #endif /* UDF_COMPLETE_DELETE */ /* select if not splitting the tag and its smaller */ if ((size_diff >= 0) && (size_diff < chosen_size_diff) && (lb_rest >= sizeof(struct desc_tag))) { /* UDF 2.3.4.2+3 specifies rules for iu size */ if ((size_diff == 0) || (size_diff >= 32)) { chosen_fid_pos = fid_pos; chosen_size = this_fidsize; chosen_size_diff = size_diff; } } } /* extend directory if no other candidate found */ if (chosen_size == 0) { chosen_fid_pos = dir_size; chosen_size = fidsize; chosen_size_diff = 0; /* special case UDF 2.00+ 2.3.4.4, no splitting up fid tag */ if (addr_type == UDF_ICB_INTERN_ALLOC) { /* pre-grow directory to see if we're to switch */ udf_grow_node(dir_node, dir_size + chosen_size); icbflags = udf_rw16(icbtag->flags); addr_type = icbflags & UDF_ICB_TAG_FLAGS_ALLOC_MASK; } /* make sure the next fid desc_tag won't be splitted */ if (addr_type != UDF_ICB_INTERN_ALLOC) { end_fid_pos = chosen_fid_pos + chosen_size; lb_rest = lb_size - (end_fid_pos % lb_size); /* pad with implementation use regid if needed */ if (lb_rest < sizeof(struct desc_tag)) chosen_size += 32; } } chosen_size_diff = chosen_size - fidsize; /* populate the FID */ memset(fid, 0, lb_size); udf_inittag(ump, &fid->tag, TAGID_FID, 0); fid->file_version_num = udf_rw16(1); /* UDF 2.3.4.1 */ fid->file_char = file_char; fid->icb = udf_node->loc; fid->icb.longad_uniqueid = udf_rw32((uint32_t) unique_id); fid->l_iu = udf_rw16(0); if (chosen_size > fidsize) { /* insert implementation-use regid to space it correctly */ fid->l_iu = udf_rw16(chosen_size_diff); /* set implementation use */ udf_set_regid((struct regid *) fid->data, IMPL_NAME); udf_add_impl_regid(ump, (struct regid *) fid->data); } /* fill in name */ unix_to_udf_name((char *) fid->data + udf_rw16(fid->l_iu), &fid->l_fi, cnp->cn_nameptr, cnp->cn_namelen, &osta_charspec); fid->tag.desc_crc_len = udf_rw16(chosen_size - UDF_DESC_TAG_LENGTH); (void) udf_validate_tag_and_crc_sums((union dscrptr *) fid); /* writeout FID/update parent directory */ error = vn_rdwr(UIO_WRITE, dvp, fid, chosen_size, chosen_fid_pos, UIO_SYSSPACE, IO_ALTSEMANTICS | IO_NODELOCKED, FSCRED, NULL, NULL); if (error) goto error_out; /* add reference counter in attached node */ if (udf_node->fe) { refcnt = udf_rw16(udf_node->fe->link_cnt); udf_node->fe->link_cnt = udf_rw16(refcnt+1); } else { KASSERT(udf_node->efe); refcnt = udf_rw16(udf_node->efe->link_cnt); udf_node->efe->link_cnt = udf_rw16(refcnt+1); } /* mark not deleted if it was... just in case, but do warn */ if (udf_node->i_flags & IN_DELETED) { printf("udf: warning, marking a file undeleted\n"); udf_node->i_flags &= ~IN_DELETED; } if (file_char & UDF_FILE_CHAR_DIR) { /* add reference counter in directory node for '..' */ if (dir_node->fe) { refcnt = udf_rw16(dir_node->fe->link_cnt); refcnt++; dir_node->fe->link_cnt = udf_rw16(refcnt); } else { KASSERT(dir_node->efe); refcnt = udf_rw16(dir_node->efe->link_cnt); refcnt++; dir_node->efe->link_cnt = udf_rw16(refcnt); } } /* append to the dirhash */ /* NOTE do not use dirent anymore or it won't match later! */ udf_to_unix_name(dirent.d_name, NAME_MAX, (char *) fid->data + udf_rw16(fid->l_iu), fid->l_fi, &osta_charspec); dirent.d_namlen = strlen(dirent.d_name); dirhash_enter(dirh, &dirent, chosen_fid_pos, udf_fidsize(fid), 1); /* note updates */ udf_node->i_flags |= IN_CHANGE | IN_MODIFY; /* | IN_CREATE? */ /* VN_KNOTE(udf_node, ...) */ udf_update(udf_node->vnode, NULL, NULL, NULL, 0); error_out: free(fid, M_TEMP); dirhash_put(dir_node->dir_hash); return error; } /* --------------------------------------------------------------------- */ /* * Each node can have an attached streamdir node though not recursively. These * are otherwise known as named substreams/named extended attributes that have * no size limitations. * * `Normal' extended attributes are indicated with a number and are recorded * in either the fe/efe descriptor itself for small descriptors or recorded in * the attached extended attribute file. Since these spaces can get * fragmented, care ought to be taken. * * Since the size of the space reserved for allocation descriptors is limited, * there is a mechanim provided for extending this space; this is done by a * special extent to allow schrinking of the allocations without breaking the * linkage to the allocation extent descriptor. */ int udf_loadvnode(struct mount *mp, struct vnode *vp, const void *key, size_t key_len, const void **new_key) { union dscrptr *dscr; struct udf_mount *ump; struct udf_node *udf_node; struct long_ad node_icb_loc, icb_loc, next_icb_loc, last_fe_icb_loc; uint64_t file_size; uint32_t lb_size, sector, dummy; int udf_file_type, dscr_type, strat, strat4096, needs_indirect; int slot, eof, error; int num_indir_followed = 0; DPRINTF(NODE, ("udf_loadvnode called\n")); udf_node = NULL; ump = VFSTOUDF(mp); KASSERT(key_len == sizeof(node_icb_loc.loc)); memset(&node_icb_loc, 0, sizeof(node_icb_loc)); node_icb_loc.len = ump->logical_vol->lb_size; memcpy(&node_icb_loc.loc, key, key_len); /* garbage check: translate udf_node_icb_loc to sectornr */ error = udf_translate_vtop(ump, &node_icb_loc, &sector, &dummy); if (error) { DPRINTF(NODE, ("\tcan't translate icb address!\n")); /* no use, this will fail anyway */ return EINVAL; } /* build udf_node (do initialise!) */ udf_node = pool_get(&udf_node_pool, PR_WAITOK); memset(udf_node, 0, sizeof(struct udf_node)); vp->v_tag = VT_UDF; vp->v_op = udf_vnodeop_p; vp->v_data = udf_node; /* initialise crosslinks, note location of fe/efe for hashing */ udf_node->ump = ump; udf_node->vnode = vp; udf_node->loc = node_icb_loc; udf_node->lockf = 0; mutex_init(&udf_node->node_mutex, MUTEX_DEFAULT, IPL_NONE); cv_init(&udf_node->node_lock, "udf_nlk"); genfs_node_init(vp, &udf_genfsops); /* inititise genfs */ udf_node->outstanding_bufs = 0; udf_node->outstanding_nodedscr = 0; udf_node->uncommitted_lbs = 0; /* check if we're fetching the root */ if (ump->fileset_desc) if (memcmp(&udf_node->loc, &ump->fileset_desc->rootdir_icb, sizeof(struct long_ad)) == 0) vp->v_vflag |= VV_ROOT; icb_loc = node_icb_loc; needs_indirect = 0; strat4096 = 0; udf_file_type = UDF_ICB_FILETYPE_UNKNOWN; file_size = 0; lb_size = udf_rw32(ump->logical_vol->lb_size); DPRINTF(NODE, ("\tstart reading descriptors\n")); do { /* try to read in fe/efe */ error = udf_read_logvol_dscr(ump, &icb_loc, &dscr); /* blank sector marks end of sequence, check this */ if ((dscr == NULL) && (!strat4096)) error = ENOENT; /* break if read error or blank sector */ if (error || (dscr == NULL)) break; /* process descriptor based on the descriptor type */ dscr_type = udf_rw16(dscr->tag.id); DPRINTF(NODE, ("\tread descriptor %d\n", dscr_type)); /* if dealing with an indirect entry, follow the link */ if (dscr_type == TAGID_INDIRECTENTRY) { needs_indirect = 0; next_icb_loc = dscr->inde.indirect_icb; udf_free_logvol_dscr(ump, &icb_loc, dscr); icb_loc = next_icb_loc; if (++num_indir_followed > UDF_MAX_INDIRS_FOLLOW) { error = EMLINK; break; } continue; } /* only file entries and extended file entries allowed here */ if ((dscr_type != TAGID_FENTRY) && (dscr_type != TAGID_EXTFENTRY)) { udf_free_logvol_dscr(ump, &icb_loc, dscr); error = ENOENT; break; } KASSERT(udf_tagsize(dscr, lb_size) == lb_size); /* choose this one */ last_fe_icb_loc = icb_loc; /* record and process/update (ext)fentry */ if (dscr_type == TAGID_FENTRY) { if (udf_node->fe) udf_free_logvol_dscr(ump, &last_fe_icb_loc, udf_node->fe); udf_node->fe = &dscr->fe; strat = udf_rw16(udf_node->fe->icbtag.strat_type); udf_file_type = udf_node->fe->icbtag.file_type; file_size = udf_rw64(udf_node->fe->inf_len); } else { if (udf_node->efe) udf_free_logvol_dscr(ump, &last_fe_icb_loc, udf_node->efe); udf_node->efe = &dscr->efe; strat = udf_rw16(udf_node->efe->icbtag.strat_type); udf_file_type = udf_node->efe->icbtag.file_type; file_size = udf_rw64(udf_node->efe->inf_len); } /* check recording strategy (structure) */ /* * Strategy 4096 is a daisy linked chain terminating with an * unrecorded sector or a TERM descriptor. The next * descriptor is to be found in the sector that follows the * current sector. */ if (strat == 4096) { strat4096 = 1; needs_indirect = 1; icb_loc.loc.lb_num = udf_rw32(icb_loc.loc.lb_num) + 1; } /* * Strategy 4 is the normal strategy and terminates, but if * we're in strategy 4096, we can't have strategy 4 mixed in */ if (strat == 4) { if (strat4096) { error = EINVAL; break; } break; /* done */ } } while (!error); /* first round of cleanup code */ if (error) { DPRINTF(NODE, ("\tnode fe/efe failed!\n")); /* recycle udf_node */ udf_dispose_node(udf_node); return EINVAL; /* error code ok? */ } DPRINTF(NODE, ("\tnode fe/efe read in fine\n")); /* assert no references to dscr anymore beyong this point */ assert((udf_node->fe) || (udf_node->efe)); dscr = NULL; /* * Remember where to record an updated version of the descriptor. If * there is a sequence of indirect entries, icb_loc will have been * updated. Its the write disipline to allocate new space and to make * sure the chain is maintained. * * `needs_indirect' flags if the next location is to be filled with * with an indirect entry. */ udf_node->write_loc = icb_loc; udf_node->needs_indirect = needs_indirect; /* * Go trough all allocations extents of this descriptor and when * encountering a redirect read in the allocation extension. These are * daisy-chained. */ UDF_LOCK_NODE(udf_node, 0); udf_node->num_extensions = 0; error = 0; slot = 0; for (;;) { udf_get_adslot(udf_node, slot, &icb_loc, &eof); DPRINTF(ADWLK, ("slot %d, eof = %d, flags = %d, len = %d, " "lb_num = %d, part = %d\n", slot, eof, UDF_EXT_FLAGS(udf_rw32(icb_loc.len)), UDF_EXT_LEN(udf_rw32(icb_loc.len)), udf_rw32(icb_loc.loc.lb_num), udf_rw16(icb_loc.loc.part_num))); if (eof) break; slot++; if (UDF_EXT_FLAGS(udf_rw32(icb_loc.len)) != UDF_EXT_REDIRECT) continue; DPRINTF(NODE, ("\tgot redirect extent\n")); if (udf_node->num_extensions >= UDF_MAX_ALLOC_EXTENTS) { DPRINTF(ALLOC, ("udf_get_node: implementation limit, " "too many allocation extensions on " "udf_node\n")); error = EINVAL; break; } /* length can only be *one* lb : UDF 2.50/2.3.7.1 */ if (UDF_EXT_LEN(udf_rw32(icb_loc.len)) != lb_size) { DPRINTF(ALLOC, ("udf_get_node: bad allocation " "extension size in udf_node\n")); error = EINVAL; break; } DPRINTF(NODE, ("read allocation extent at lb_num %d\n", UDF_EXT_LEN(udf_rw32(icb_loc.loc.lb_num)))); /* load in allocation extent */ error = udf_read_logvol_dscr(ump, &icb_loc, &dscr); if (error || (dscr == NULL)) break; /* process read-in descriptor */ dscr_type = udf_rw16(dscr->tag.id); if (dscr_type != TAGID_ALLOCEXTENT) { udf_free_logvol_dscr(ump, &icb_loc, dscr); error = ENOENT; break; } DPRINTF(NODE, ("\trecording redirect extent\n")); udf_node->ext[udf_node->num_extensions] = &dscr->aee; udf_node->ext_loc[udf_node->num_extensions] = icb_loc; udf_node->num_extensions++; } /* while */ UDF_UNLOCK_NODE(udf_node, 0); /* second round of cleanup code */ if (error) { /* recycle udf_node */ udf_dispose_node(udf_node); return EINVAL; /* error code ok? */ } DPRINTF(NODE, ("\tnode read in fine\n")); /* * Translate UDF filetypes into vnode types. * * Systemfiles like the meta main and mirror files are not treated as * normal files, so we type them as having no type. UDF dictates that * they are not allowed to be visible. */ switch (udf_file_type) { case UDF_ICB_FILETYPE_DIRECTORY : case UDF_ICB_FILETYPE_STREAMDIR : vp->v_type = VDIR; break; case UDF_ICB_FILETYPE_BLOCKDEVICE : vp->v_type = VBLK; break; case UDF_ICB_FILETYPE_CHARDEVICE : vp->v_type = VCHR; break; case UDF_ICB_FILETYPE_SOCKET : vp->v_type = VSOCK; break; case UDF_ICB_FILETYPE_FIFO : vp->v_type = VFIFO; break; case UDF_ICB_FILETYPE_SYMLINK : vp->v_type = VLNK; break; case UDF_ICB_FILETYPE_VAT : case UDF_ICB_FILETYPE_META_MAIN : case UDF_ICB_FILETYPE_META_MIRROR : vp->v_type = VNON; break; case UDF_ICB_FILETYPE_RANDOMACCESS : case UDF_ICB_FILETYPE_REALTIME : vp->v_type = VREG; break; default: /* YIKES, something else */ vp->v_type = VNON; } /* TODO specfs, fifofs etc etc. vnops setting */ /* don't forget to set vnode's v_size */ uvm_vnp_setsize(vp, file_size); /* TODO ext attr and streamdir udf_nodes */ *new_key = &udf_node->loc.loc; return 0; } int udf_get_node(struct udf_mount *ump, struct long_ad *node_icb_loc, struct udf_node **udf_noderes) { int error; struct vnode *vp; error = vcache_get(ump->vfs_mountp, &node_icb_loc->loc, sizeof(node_icb_loc->loc), &vp); if (error) return error; error = vn_lock(vp, LK_EXCLUSIVE); if (error) { vrele(vp); return error; } *udf_noderes = VTOI(vp); return 0; } /* --------------------------------------------------------------------- */ int udf_writeout_node(struct udf_node *udf_node, int waitfor) { union dscrptr *dscr; struct long_ad *loc; int extnr, error; DPRINTF(NODE, ("udf_writeout_node called\n")); KASSERT(udf_node->outstanding_bufs == 0); KASSERT(udf_node->outstanding_nodedscr == 0); KASSERT(LIST_EMPTY(&udf_node->vnode->v_dirtyblkhd)); if (udf_node->i_flags & IN_DELETED) { DPRINTF(NODE, ("\tnode deleted; not writing out\n")); udf_cleanup_reservation(udf_node); return 0; } /* lock node; unlocked in callback */ UDF_LOCK_NODE(udf_node, 0); /* remove pending reservations, we're written out */ udf_cleanup_reservation(udf_node); /* at least one descriptor writeout */ udf_node->outstanding_nodedscr = 1; /* we're going to write out the descriptor so clear the flags */ udf_node->i_flags &= ~(IN_MODIFIED | IN_ACCESSED); /* if we were rebuild, write out the allocation extents */ if (udf_node->i_flags & IN_NODE_REBUILD) { /* mark outstanding node descriptors and issue them */ udf_node->outstanding_nodedscr += udf_node->num_extensions; for (extnr = 0; extnr < udf_node->num_extensions; extnr++) { loc = &udf_node->ext_loc[extnr]; dscr = (union dscrptr *) udf_node->ext[extnr]; error = udf_write_logvol_dscr(udf_node, dscr, loc, 0); if (error) return error; } /* mark allocation extents written out */ udf_node->i_flags &= ~(IN_NODE_REBUILD); } if (udf_node->fe) { KASSERT(udf_node->efe == NULL); dscr = (union dscrptr *) udf_node->fe; } else { KASSERT(udf_node->efe); KASSERT(udf_node->fe == NULL); dscr = (union dscrptr *) udf_node->efe; } KASSERT(dscr); loc = &udf_node->write_loc; error = udf_write_logvol_dscr(udf_node, dscr, loc, waitfor); return error; } /* --------------------------------------------------------------------- */ int udf_dispose_node(struct udf_node *udf_node) { struct vnode *vp; int extnr; DPRINTF(NODE, ("udf_dispose_node called on node %p\n", udf_node)); if (!udf_node) { DPRINTF(NODE, ("UDF: Dispose node on node NULL, ignoring\n")); return 0; } vp = udf_node->vnode; #ifdef DIAGNOSTIC if (vp->v_numoutput) panic("disposing UDF node with pending I/O's, udf_node = %p, " "v_numoutput = %d", udf_node, vp->v_numoutput); #endif udf_cleanup_reservation(udf_node); /* TODO extended attributes and streamdir */ /* remove dirhash if present */ dirhash_purge(&udf_node->dir_hash); /* destroy our lock */ mutex_destroy(&udf_node->node_mutex); cv_destroy(&udf_node->node_lock); /* dissociate our udf_node from the vnode */ genfs_node_destroy(udf_node->vnode); mutex_enter(vp->v_interlock); vp->v_data = NULL; mutex_exit(vp->v_interlock); /* free associated memory and the node itself */ for (extnr = 0; extnr < udf_node->num_extensions; extnr++) { udf_free_logvol_dscr(udf_node->ump, &udf_node->ext_loc[extnr], udf_node->ext[extnr]); udf_node->ext[extnr] = (void *) 0xdeadcccc; } if (udf_node->fe) udf_free_logvol_dscr(udf_node->ump, &udf_node->loc, udf_node->fe); if (udf_node->efe) udf_free_logvol_dscr(udf_node->ump, &udf_node->loc, udf_node->efe); udf_node->fe = (void *) 0xdeadaaaa; udf_node->efe = (void *) 0xdeadbbbb; udf_node->ump = (void *) 0xdeadbeef; pool_put(&udf_node_pool, udf_node); return 0; } /* * create a new node using the specified dvp, vap and cnp. * This allows special files to be created. Use with care. */ int udf_newvnode(struct mount *mp, struct vnode *dvp, struct vnode *vp, struct vattr *vap, kauth_cred_t cred, size_t *key_len, const void **new_key) { union dscrptr *dscr; struct udf_node *dir_node = VTOI(dvp); struct udf_node *udf_node; struct udf_mount *ump = dir_node->ump; struct long_ad node_icb_loc; uint64_t parent_unique_id; uint64_t lmapping; uint32_t lb_size, lb_num; uint16_t vpart_num; uid_t uid; gid_t gid, parent_gid; int (**vnodeops)(void *); int udf_file_type, fid_size, error; vnodeops = udf_vnodeop_p; udf_file_type = UDF_ICB_FILETYPE_RANDOMACCESS; switch (vap->va_type) { case VREG : udf_file_type = UDF_ICB_FILETYPE_RANDOMACCESS; break; case VDIR : udf_file_type = UDF_ICB_FILETYPE_DIRECTORY; break; case VLNK : udf_file_type = UDF_ICB_FILETYPE_SYMLINK; break; case VBLK : udf_file_type = UDF_ICB_FILETYPE_BLOCKDEVICE; /* specfs */ return ENOTSUP; break; case VCHR : udf_file_type = UDF_ICB_FILETYPE_CHARDEVICE; /* specfs */ return ENOTSUP; break; case VFIFO : udf_file_type = UDF_ICB_FILETYPE_FIFO; /* fifofs */ return ENOTSUP; break; case VSOCK : udf_file_type = UDF_ICB_FILETYPE_SOCKET; return ENOTSUP; break; case VNON : case VBAD : default : /* nothing; can we even create these? */ return EINVAL; } lb_size = udf_rw32(ump->logical_vol->lb_size); /* reserve space for one logical block */ vpart_num = ump->node_part; error = udf_reserve_space(ump, NULL, UDF_C_NODE, vpart_num, 1, /* can_fail */ true); if (error) return error; /* allocate node */ error = udf_allocate_space(ump, NULL, UDF_C_NODE, vpart_num, 1, &lmapping); if (error) { udf_do_unreserve_space(ump, NULL, vpart_num, 1); return error; } lb_num = lmapping; /* initialise pointer to location */ memset(&node_icb_loc, 0, sizeof(struct long_ad)); node_icb_loc.len = udf_rw32(lb_size); node_icb_loc.loc.lb_num = udf_rw32(lb_num); node_icb_loc.loc.part_num = udf_rw16(vpart_num); /* build udf_node (do initialise!) */ udf_node = pool_get(&udf_node_pool, PR_WAITOK); memset(udf_node, 0, sizeof(struct udf_node)); /* initialise crosslinks, note location of fe/efe for hashing */ /* bugalert: synchronise with udf_get_node() */ udf_node->ump = ump; udf_node->vnode = vp; vp->v_data = udf_node; udf_node->loc = node_icb_loc; udf_node->write_loc = node_icb_loc; udf_node->lockf = 0; mutex_init(&udf_node->node_mutex, MUTEX_DEFAULT, IPL_NONE); cv_init(&udf_node->node_lock, "udf_nlk"); udf_node->outstanding_bufs = 0; udf_node->outstanding_nodedscr = 0; udf_node->uncommitted_lbs = 0; vp->v_tag = VT_UDF; vp->v_op = vnodeops; /* initialise genfs */ genfs_node_init(vp, &udf_genfsops); /* get parent's unique ID for refering '..' if its a directory */ if (dir_node->fe) { parent_unique_id = udf_rw64(dir_node->fe->unique_id); parent_gid = (gid_t) udf_rw32(dir_node->fe->gid); } else { parent_unique_id = udf_rw64(dir_node->efe->unique_id); parent_gid = (gid_t) udf_rw32(dir_node->efe->gid); } /* get descriptor */ udf_create_logvol_dscr(ump, udf_node, &node_icb_loc, &dscr); /* choose a fe or an efe for it */ if (udf_rw16(ump->logical_vol->tag.descriptor_ver) == 2) { udf_node->fe = &dscr->fe; fid_size = udf_create_new_fe(ump, udf_node->fe, udf_file_type, &udf_node->loc, &dir_node->loc, parent_unique_id); /* TODO add extended attribute for creation time */ } else { udf_node->efe = &dscr->efe; fid_size = udf_create_new_efe(ump, udf_node->efe, udf_file_type, &udf_node->loc, &dir_node->loc, parent_unique_id); } KASSERT(dscr->tag.tag_loc == udf_node->loc.loc.lb_num); /* update vnode's size and type */ vp->v_type = vap->va_type; uvm_vnp_setsize(vp, fid_size); /* set access mode */ udf_setaccessmode(udf_node, vap->va_mode); /* set ownership */ uid = kauth_cred_geteuid(cred); gid = parent_gid; udf_setownership(udf_node, uid, gid); *key_len = sizeof(udf_node->loc.loc);; *new_key = &udf_node->loc.loc; return 0; } int udf_create_node(struct vnode *dvp, struct vnode **vpp, struct vattr *vap, struct componentname *cnp) { struct udf_node *udf_node, *dir_node = VTOI(dvp); struct udf_mount *ump = dir_node->ump; int error; error = vcache_new(dvp->v_mount, dvp, vap, cnp->cn_cred, vpp); if (error) return error; udf_node = VTOI(*vpp); error = udf_dir_attach(ump, dir_node, udf_node, vap, cnp); if (error) { struct long_ad *node_icb_loc = &udf_node->loc; uint32_t lb_num = udf_rw32(node_icb_loc->loc.lb_num); uint16_t vpart_num = udf_rw16(node_icb_loc->loc.part_num); /* free disc allocation for node */ udf_free_allocated_space(ump, lb_num, vpart_num, 1); /* recycle udf_node */ udf_dispose_node(udf_node); vrele(*vpp); *vpp = NULL; return error; } /* adjust file count */ udf_adjust_filecount(udf_node, 1); return 0; } /* --------------------------------------------------------------------- */ static void udf_free_descriptor_space(struct udf_node *udf_node, struct long_ad *loc, void *mem) { struct udf_mount *ump = udf_node->ump; uint32_t lb_size, lb_num, len, num_lb; uint16_t vpart_num; /* is there really one? */ if (mem == NULL) return; /* got a descriptor here */ len = UDF_EXT_LEN(udf_rw32(loc->len)); lb_num = udf_rw32(loc->loc.lb_num); vpart_num = udf_rw16(loc->loc.part_num); lb_size = udf_rw32(ump->logical_vol->lb_size); num_lb = (len + lb_size -1) / lb_size; udf_free_allocated_space(ump, lb_num, vpart_num, num_lb); } void udf_delete_node(struct udf_node *udf_node) { void *dscr; struct long_ad *loc; int extnr, lvint, dummy; /* paranoia check on integrity; should be open!; we could panic */ lvint = udf_rw32(udf_node->ump->logvol_integrity->integrity_type); if (lvint == UDF_INTEGRITY_CLOSED) printf("\tIntegrity was CLOSED!\n"); /* whatever the node type, change its size to zero */ (void) udf_resize_node(udf_node, 0, &dummy); /* force it to be `clean'; no use writing it out */ udf_node->i_flags &= ~(IN_MODIFIED | IN_ACCESSED | IN_ACCESS | IN_CHANGE | IN_UPDATE | IN_MODIFY); /* adjust file count */ udf_adjust_filecount(udf_node, -1); /* * Free its allocated descriptors; memory will be released when * vop_reclaim() is called. */ loc = &udf_node->loc; dscr = udf_node->fe; udf_free_descriptor_space(udf_node, loc, dscr); dscr = udf_node->efe; udf_free_descriptor_space(udf_node, loc, dscr); for (extnr = 0; extnr < UDF_MAX_ALLOC_EXTENTS; extnr++) { dscr = udf_node->ext[extnr]; loc = &udf_node->ext_loc[extnr]; udf_free_descriptor_space(udf_node, loc, dscr); } } /* --------------------------------------------------------------------- */ /* set new filesize; node but be LOCKED on entry and is locked on exit */ int udf_resize_node(struct udf_node *udf_node, uint64_t new_size, int *extended) { struct file_entry *fe = udf_node->fe; struct extfile_entry *efe = udf_node->efe; uint64_t file_size; int error; if (fe) { file_size = udf_rw64(fe->inf_len); } else { assert(udf_node->efe); file_size = udf_rw64(efe->inf_len); } DPRINTF(ATTR, ("\tchanging file length from %"PRIu64" to %"PRIu64"\n", file_size, new_size)); /* if not changing, we're done */ if (file_size == new_size) return 0; *extended = (new_size > file_size); if (*extended) { error = udf_grow_node(udf_node, new_size); } else { error = udf_shrink_node(udf_node, new_size); } return error; } /* --------------------------------------------------------------------- */ void udf_itimes(struct udf_node *udf_node, struct timespec *acc, struct timespec *mod, struct timespec *birth) { struct timespec now; struct file_entry *fe; struct extfile_entry *efe; struct filetimes_extattr_entry *ft_extattr; struct timestamp *atime, *mtime, *attrtime, *ctime; struct timestamp fe_ctime; struct timespec cur_birth; uint32_t offset, a_l; uint8_t *filedata; int error; /* protect against rogue values */ if (!udf_node) return; fe = udf_node->fe; efe = udf_node->efe; if (!(udf_node->i_flags & (IN_ACCESS|IN_CHANGE|IN_UPDATE|IN_MODIFY))) return; /* get descriptor information */ if (fe) { atime = &fe->atime; mtime = &fe->mtime; attrtime = &fe->attrtime; filedata = fe->data; /* initial save dummy setting */ ctime = &fe_ctime; /* check our extended attribute if present */ error = udf_extattr_search_intern(udf_node, UDF_FILETIMES_ATTR_NO, "", &offset, &a_l); if (!error) { ft_extattr = (struct filetimes_extattr_entry *) (filedata + offset); if (ft_extattr->existence & UDF_FILETIMES_FILE_CREATION) ctime = &ft_extattr->times[0]; } /* TODO create the extended attribute if not found ? */ } else { assert(udf_node->efe); atime = &efe->atime; mtime = &efe->mtime; attrtime = &efe->attrtime; ctime = &efe->ctime; } vfs_timestamp(&now); /* set access time */ if (udf_node->i_flags & IN_ACCESS) { if (acc == NULL) acc = &now; udf_timespec_to_timestamp(acc, atime); } /* set modification time */ if (udf_node->i_flags & (IN_UPDATE | IN_MODIFY)) { if (mod == NULL) mod = &now; udf_timespec_to_timestamp(mod, mtime); /* ensure birthtime is older than set modification! */ udf_timestamp_to_timespec(udf_node->ump, ctime, &cur_birth); if ((cur_birth.tv_sec > mod->tv_sec) || ((cur_birth.tv_sec == mod->tv_sec) && (cur_birth.tv_nsec > mod->tv_nsec))) { udf_timespec_to_timestamp(mod, ctime); } } /* update birthtime if specified */ /* XXX we assume here that given birthtime is older than mod */ if (birth && (birth->tv_sec != VNOVAL)) { udf_timespec_to_timestamp(birth, ctime); } /* set change time */ if (udf_node->i_flags & (IN_CHANGE | IN_MODIFY)) udf_timespec_to_timestamp(&now, attrtime); /* notify updates to the node itself */ if (udf_node->i_flags & (IN_ACCESS | IN_MODIFY)) udf_node->i_flags |= IN_ACCESSED; if (udf_node->i_flags & (IN_UPDATE | IN_CHANGE)) udf_node->i_flags |= IN_MODIFIED; /* clear modification flags */ udf_node->i_flags &= ~(IN_ACCESS | IN_CHANGE | IN_UPDATE | IN_MODIFY); } /* --------------------------------------------------------------------- */ int udf_update(struct vnode *vp, struct timespec *acc, struct timespec *mod, struct timespec *birth, int updflags) { union dscrptr *dscrptr; struct udf_node *udf_node = VTOI(vp); struct udf_mount *ump = udf_node->ump; struct regid *impl_id; int mnt_async = (vp->v_mount->mnt_flag & MNT_ASYNC); int waitfor, flags; #ifdef DEBUG char bits[128]; DPRINTF(CALL, ("udf_update(node, %p, %p, %p, %d)\n", acc, mod, birth, updflags)); snprintb(bits, sizeof(bits), IN_FLAGBITS, udf_node->i_flags); DPRINTF(CALL, ("\tnode flags %s\n", bits)); DPRINTF(CALL, ("\t\tmnt_async = %d\n", mnt_async)); #endif /* set our times */ udf_itimes(udf_node, acc, mod, birth); /* set our implementation id */ if (udf_node->fe) { dscrptr = (union dscrptr *) udf_node->fe; impl_id = &udf_node->fe->imp_id; } else { dscrptr = (union dscrptr *) udf_node->efe; impl_id = &udf_node->efe->imp_id; } /* set our ID */ udf_set_regid(impl_id, IMPL_NAME); udf_add_impl_regid(ump, impl_id); /* update our crc! on RMW we are not allowed to change a thing */ udf_validate_tag_and_crc_sums(dscrptr); /* if called when mounted readonly, never write back */ if (vp->v_mount->mnt_flag & MNT_RDONLY) return 0; /* check if the node is dirty 'enough'*/ if (updflags & UPDATE_CLOSE) { flags = udf_node->i_flags & (IN_MODIFIED | IN_ACCESSED); } else { flags = udf_node->i_flags & IN_MODIFIED; } if (flags == 0) return 0; /* determine if we need to write sync or async */ waitfor = 0; if ((flags & IN_MODIFIED) && (mnt_async == 0)) { /* sync mounted */ waitfor = updflags & UPDATE_WAIT; if (updflags & UPDATE_DIROP) waitfor |= UPDATE_WAIT; } if (waitfor) return VOP_FSYNC(vp, FSCRED, FSYNC_WAIT, 0,0); return 0; } /* --------------------------------------------------------------------- */ /* * Read one fid and process it into a dirent and advance to the next (*fid) * has to be allocated a logical block in size, (*dirent) struct dirent length */ int udf_read_fid_stream(struct vnode *vp, uint64_t *offset, struct fileid_desc *fid, struct dirent *dirent) { struct udf_node *dir_node = VTOI(vp); struct udf_mount *ump = dir_node->ump; struct file_entry *fe = dir_node->fe; struct extfile_entry *efe = dir_node->efe; uint32_t fid_size, lb_size; uint64_t file_size; char *fid_name; int enough, error; assert(fid); assert(dirent); assert(dir_node); assert(offset); assert(*offset != 1); DPRINTF(FIDS, ("read_fid_stream called at offset %"PRIu64"\n", *offset)); /* check if we're past the end of the directory */ if (fe) { file_size = udf_rw64(fe->inf_len); } else { assert(dir_node->efe); file_size = udf_rw64(efe->inf_len); } if (*offset >= file_size) return EINVAL; /* get maximum length of FID descriptor */ lb_size = udf_rw32(ump->logical_vol->lb_size); /* initialise return values */ fid_size = 0; memset(dirent, 0, sizeof(struct dirent)); memset(fid, 0, lb_size); enough = (file_size - (*offset) >= UDF_FID_SIZE); if (!enough) { /* short dir ... */ return EIO; } error = vn_rdwr(UIO_READ, vp, fid, MIN(file_size - (*offset), lb_size), *offset, UIO_SYSSPACE, IO_ALTSEMANTICS | IO_NODELOCKED, FSCRED, NULL, NULL); if (error) return error; DPRINTF(FIDS, ("\tfid piece read in fine\n")); /* * Check if we got a whole descriptor. * TODO Try to `resync' directory stream when something is very wrong. */ /* check if our FID header is OK */ error = udf_check_tag(fid); if (error) { goto brokendir; } DPRINTF(FIDS, ("\ttag check ok\n")); if (udf_rw16(fid->tag.id) != TAGID_FID) { error = EIO; goto brokendir; } DPRINTF(FIDS, ("\ttag checked ok: got TAGID_FID\n")); /* check for length */ fid_size = udf_fidsize(fid); enough = (file_size - (*offset) >= fid_size); if (!enough) { error = EIO; goto brokendir; } DPRINTF(FIDS, ("\tthe complete fid is read in\n")); /* check FID contents */ error = udf_check_tag_payload((union dscrptr *) fid, lb_size); brokendir: if (error) { /* note that is sometimes a bit quick to report */ printf("UDF: BROKEN DIRECTORY ENTRY\n"); /* RESYNC? */ /* TODO: use udf_resync_fid_stream */ return EIO; } DPRINTF(FIDS, ("\tpayload checked ok\n")); /* we got a whole and valid descriptor! */ DPRINTF(FIDS, ("\tinterpret FID\n")); /* create resulting dirent structure */ fid_name = (char *) fid->data + udf_rw16(fid->l_iu); udf_to_unix_name(dirent->d_name, NAME_MAX, fid_name, fid->l_fi, &ump->logical_vol->desc_charset); /* '..' has no name, so provide one */ if (fid->file_char & UDF_FILE_CHAR_PAR) strcpy(dirent->d_name, ".."); dirent->d_fileno = udf_get_node_id(&fid->icb); /* inode hash XXX */ dirent->d_namlen = strlen(dirent->d_name); dirent->d_reclen = _DIRENT_SIZE(dirent); /* * Note that its not worth trying to go for the filetypes now... its * too expensive too */ dirent->d_type = DT_UNKNOWN; /* initial guess for filetype we can make */ if (fid->file_char & UDF_FILE_CHAR_DIR) dirent->d_type = DT_DIR; /* advance */ *offset += fid_size; return error; } /* --------------------------------------------------------------------- */ static void udf_sync_pass(struct udf_mount *ump, kauth_cred_t cred, int pass, int *ndirty) { struct udf_node *udf_node, *n_udf_node; struct vnode *vp; int vdirty, error; KASSERT(mutex_owned(&ump->sync_lock)); DPRINTF(SYNC, ("sync_pass %d\n", pass)); udf_node = RB_TREE_MIN(&ump->udf_node_tree); for (;udf_node; udf_node = n_udf_node) { DPRINTF(SYNC, (".")); vp = udf_node->vnode; n_udf_node = rb_tree_iterate(&ump->udf_node_tree, udf_node, RB_DIR_RIGHT); error = vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT); if (error) { KASSERT(error == EBUSY); *ndirty += 1; continue; } switch (pass) { case 1: VOP_FSYNC(vp, cred, 0 | FSYNC_DATAONLY,0,0); break; case 2: vdirty = vp->v_numoutput; if (vp->v_tag == VT_UDF) vdirty += udf_node->outstanding_bufs + udf_node->outstanding_nodedscr; if (vdirty == 0) VOP_FSYNC(vp, cred, 0,0,0); *ndirty += vdirty; break; case 3: vdirty = vp->v_numoutput; if (vp->v_tag == VT_UDF) vdirty += udf_node->outstanding_bufs + udf_node->outstanding_nodedscr; *ndirty += vdirty; break; } VOP_UNLOCK(vp); } DPRINTF(SYNC, ("END sync_pass %d\n", pass)); } static bool udf_sync_selector(void *cl, struct vnode *vp) { struct udf_node *udf_node = VTOI(vp); if (vp->v_vflag & VV_SYSTEM) return false; if (vp->v_type == VNON) return false; if (udf_node == NULL) return false; if ((udf_node->i_flags & (IN_ACCESSED | IN_UPDATE | IN_MODIFIED)) == 0) return false; if (LIST_EMPTY(&vp->v_dirtyblkhd) && UVM_OBJ_IS_CLEAN(&vp->v_uobj)) return false; return true; } void udf_do_sync(struct udf_mount *ump, kauth_cred_t cred, int waitfor) { struct vnode_iterator *marker; struct vnode *vp; struct udf_node *udf_node, *udf_next_node; int dummy, ndirty; if (waitfor == MNT_LAZY) return; mutex_enter(&ump->sync_lock); /* Fill the rbtree with nodes to sync. */ vfs_vnode_iterator_init(ump->vfs_mountp, &marker); while ((vp = vfs_vnode_iterator_next(marker, udf_sync_selector, NULL)) != NULL) { udf_node = VTOI(vp); udf_node->i_flags |= IN_SYNCED; rb_tree_insert_node(&ump->udf_node_tree, udf_node); } vfs_vnode_iterator_destroy(marker); dummy = 0; DPRINTF(CALL, ("issue VOP_FSYNC(DATA only) on all nodes\n")); DPRINTF(SYNC, ("issue VOP_FSYNC(DATA only) on all nodes\n")); udf_sync_pass(ump, cred, 1, &dummy); DPRINTF(CALL, ("issue VOP_FSYNC(COMPLETE) on all finished nodes\n")); DPRINTF(SYNC, ("issue VOP_FSYNC(COMPLETE) on all finished nodes\n")); udf_sync_pass(ump, cred, 2, &dummy); if (waitfor == MNT_WAIT) { recount: ndirty = ump->devvp->v_numoutput; DPRINTF(SYNC, ("counting pending blocks: on devvp %d\n", ndirty)); udf_sync_pass(ump, cred, 3, &ndirty); DPRINTF(SYNC, ("counted num dirty pending blocks %d\n", ndirty)); if (ndirty) { /* 1/4 second wait */ kpause("udfsync2", false, hz/4, NULL); goto recount; } } /* Clean the rbtree. */ for (udf_node = RB_TREE_MIN(&ump->udf_node_tree); udf_node; udf_node = udf_next_node) { udf_next_node = rb_tree_iterate(&ump->udf_node_tree, udf_node, RB_DIR_RIGHT); rb_tree_remove_node(&ump->udf_node_tree, udf_node); udf_node->i_flags &= ~IN_SYNCED; vrele(udf_node->vnode); } mutex_exit(&ump->sync_lock); } /* --------------------------------------------------------------------- */ /* * Read and write file extent in/from the buffer. * * The splitup of the extent into seperate request-buffers is to minimise * copying around as much as possible. * * block based file reading and writing */ static int udf_read_internal(struct udf_node *node, uint8_t *blob) { struct udf_mount *ump; struct file_entry *fe = node->fe; struct extfile_entry *efe = node->efe; uint64_t inflen; uint32_t sector_size; uint8_t *pos; int icbflags, addr_type; /* get extent and do some paranoia checks */ ump = node->ump; sector_size = ump->discinfo.sector_size; if (fe) { inflen = udf_rw64(fe->inf_len); pos = &fe->data[0] + udf_rw32(fe->l_ea); icbflags = udf_rw16(fe->icbtag.flags); } else { assert(node->efe); inflen = udf_rw64(efe->inf_len); pos = &efe->data[0] + udf_rw32(efe->l_ea); icbflags = udf_rw16(efe->icbtag.flags); } addr_type = icbflags & UDF_ICB_TAG_FLAGS_ALLOC_MASK; assert(addr_type == UDF_ICB_INTERN_ALLOC); __USE(addr_type); assert(inflen < sector_size); /* copy out info */ memset(blob, 0, sector_size); memcpy(blob, pos, inflen); return 0; } static int udf_write_internal(struct udf_node *node, uint8_t *blob) { struct udf_mount *ump; struct file_entry *fe = node->fe; struct extfile_entry *efe = node->efe; uint64_t inflen; uint32_t sector_size; uint8_t *pos; int icbflags, addr_type; /* get extent and do some paranoia checks */ ump = node->ump; sector_size = ump->discinfo.sector_size; if (fe) { inflen = udf_rw64(fe->inf_len); pos = &fe->data[0] + udf_rw32(fe->l_ea); icbflags = udf_rw16(fe->icbtag.flags); } else { assert(node->efe); inflen = udf_rw64(efe->inf_len); pos = &efe->data[0] + udf_rw32(efe->l_ea); icbflags = udf_rw16(efe->icbtag.flags); } addr_type = icbflags & UDF_ICB_TAG_FLAGS_ALLOC_MASK; assert(addr_type == UDF_ICB_INTERN_ALLOC); __USE(addr_type); assert(inflen < sector_size); __USE(sector_size); /* copy in blob */ /* memset(pos, 0, inflen); */ memcpy(pos, blob, inflen); return 0; } void udf_read_filebuf(struct udf_node *udf_node, struct buf *buf) { struct buf *nestbuf; struct udf_mount *ump = udf_node->ump; uint64_t *mapping; uint64_t run_start; uint32_t sector_size; uint32_t buf_offset, sector, rbuflen, rblk; uint32_t from, lblkno; uint32_t sectors; uint8_t *buf_pos; int error, run_length, what; sector_size = udf_node->ump->discinfo.sector_size; from = buf->b_blkno; sectors = buf->b_bcount / sector_size; what = udf_get_c_type(udf_node); /* assure we have enough translation slots */ KASSERT(buf->b_bcount / sector_size <= UDF_MAX_MAPPINGS); KASSERT(MAXPHYS / sector_size <= UDF_MAX_MAPPINGS); if (sectors > UDF_MAX_MAPPINGS) { printf("udf_read_filebuf: implementation limit on bufsize\n"); buf->b_error = EIO; biodone(buf); return; } mapping = malloc(sizeof(*mapping) * UDF_MAX_MAPPINGS, M_TEMP, M_WAITOK); error = 0; DPRINTF(READ, ("\ttranslate %d-%d\n", from, sectors)); error = udf_translate_file_extent(udf_node, from, sectors, mapping); if (error) { buf->b_error = error; biodone(buf); goto out; } DPRINTF(READ, ("\ttranslate extent went OK\n")); /* pre-check if its an internal */ if (*mapping == UDF_TRANS_INTERN) { error = udf_read_internal(udf_node, (uint8_t *) buf->b_data); if (error) buf->b_error = error; biodone(buf); goto out; } DPRINTF(READ, ("\tnot intern\n")); #ifdef DEBUG if (udf_verbose & UDF_DEBUG_TRANSLATE) { printf("Returned translation table:\n"); for (sector = 0; sector < sectors; sector++) { printf("%d : %"PRIu64"\n", sector, mapping[sector]); } } #endif /* request read-in of data from disc sheduler */ buf->b_resid = buf->b_bcount; for (sector = 0; sector < sectors; sector++) { buf_offset = sector * sector_size; buf_pos = (uint8_t *) buf->b_data + buf_offset; DPRINTF(READ, ("\tprocessing rel sector %d\n", sector)); /* check if its zero or unmapped to stop reading */ switch (mapping[sector]) { case UDF_TRANS_UNMAPPED: case UDF_TRANS_ZERO: /* copy zero sector TODO runlength like below */ memset(buf_pos, 0, sector_size); DPRINTF(READ, ("\treturning zero sector\n")); nestiobuf_done(buf, sector_size, 0); break; default : DPRINTF(READ, ("\tread sector " "%"PRIu64"\n", mapping[sector])); lblkno = from + sector; run_start = mapping[sector]; run_length = 1; while (sector < sectors-1) { if (mapping[sector+1] != mapping[sector]+1) break; run_length++; sector++; } /* * nest an iobuf and mark it for async reading. Since * we're using nested buffers, they can't be cached by * design. */ rbuflen = run_length * sector_size; rblk = run_start * (sector_size/DEV_BSIZE); nestbuf = getiobuf(NULL, true); nestiobuf_setup(buf, nestbuf, buf_offset, rbuflen); /* nestbuf is B_ASYNC */ /* identify this nestbuf */ nestbuf->b_lblkno = lblkno; assert(nestbuf->b_vp == udf_node->vnode); /* CD shedules on raw blkno */ nestbuf->b_blkno = rblk; nestbuf->b_proc = NULL; nestbuf->b_rawblkno = rblk; nestbuf->b_udf_c_type = what; udf_discstrat_queuebuf(ump, nestbuf); } } out: /* if we're synchronously reading, wait for the completion */ if ((buf->b_flags & B_ASYNC) == 0) biowait(buf); DPRINTF(READ, ("\tend of read_filebuf\n")); free(mapping, M_TEMP); return; } void udf_write_filebuf(struct udf_node *udf_node, struct buf *buf) { struct buf *nestbuf; struct udf_mount *ump = udf_node->ump; uint64_t *mapping; uint64_t run_start; uint32_t lb_size; uint32_t buf_offset, lb_num, rbuflen, rblk; uint32_t from, lblkno; uint32_t num_lb; int error, run_length, what, s; lb_size = udf_rw32(udf_node->ump->logical_vol->lb_size); from = buf->b_blkno; num_lb = buf->b_bcount / lb_size; what = udf_get_c_type(udf_node); /* assure we have enough translation slots */ KASSERT(buf->b_bcount / lb_size <= UDF_MAX_MAPPINGS); KASSERT(MAXPHYS / lb_size <= UDF_MAX_MAPPINGS); if (num_lb > UDF_MAX_MAPPINGS) { printf("udf_write_filebuf: implementation limit on bufsize\n"); buf->b_error = EIO; biodone(buf); return; } mapping = malloc(sizeof(*mapping) * UDF_MAX_MAPPINGS, M_TEMP, M_WAITOK); error = 0; DPRINTF(WRITE, ("\ttranslate %d-%d\n", from, num_lb)); error = udf_translate_file_extent(udf_node, from, num_lb, mapping); if (error) { buf->b_error = error; biodone(buf); goto out; } DPRINTF(WRITE, ("\ttranslate extent went OK\n")); /* if its internally mapped, we can write it in the descriptor itself */ if (*mapping == UDF_TRANS_INTERN) { /* TODO paranoia check if we ARE going to have enough space */ error = udf_write_internal(udf_node, (uint8_t *) buf->b_data); if (error) buf->b_error = error; biodone(buf); goto out; } DPRINTF(WRITE, ("\tnot intern\n")); /* request write out of data to disc sheduler */ buf->b_resid = buf->b_bcount; for (lb_num = 0; lb_num < num_lb; lb_num++) { buf_offset = lb_num * lb_size; DPRINTF(WRITE, ("\tprocessing rel lb_num %d\n", lb_num)); /* * Mappings are not that important here. Just before we write * the lb_num we late-allocate them when needed and update the * mapping in the udf_node. */ /* XXX why not ignore the mapping altogether ? */ DPRINTF(WRITE, ("\twrite lb_num " "%"PRIu64, mapping[lb_num])); lblkno = from + lb_num; run_start = mapping[lb_num]; run_length = 1; while (lb_num < num_lb-1) { if (mapping[lb_num+1] != mapping[lb_num]+1) if (mapping[lb_num+1] != mapping[lb_num]) break; run_length++; lb_num++; } DPRINTF(WRITE, ("+ %d\n", run_length)); /* nest an iobuf on the master buffer for the extent */ rbuflen = run_length * lb_size; rblk = run_start * (lb_size/DEV_BSIZE); nestbuf = getiobuf(NULL, true); nestiobuf_setup(buf, nestbuf, buf_offset, rbuflen); /* nestbuf is B_ASYNC */ /* identify this nestbuf */ nestbuf->b_lblkno = lblkno; KASSERT(nestbuf->b_vp == udf_node->vnode); /* CD shedules on raw blkno */ nestbuf->b_blkno = rblk; nestbuf->b_proc = NULL; nestbuf->b_rawblkno = rblk; nestbuf->b_udf_c_type = what; /* increment our outstanding bufs counter */ s = splbio(); udf_node->outstanding_bufs++; splx(s); udf_discstrat_queuebuf(ump, nestbuf); } out: /* if we're synchronously writing, wait for the completion */ if ((buf->b_flags & B_ASYNC) == 0) biowait(buf); DPRINTF(WRITE, ("\tend of write_filebuf\n")); free(mapping, M_TEMP); return; } /* --------------------------------------------------------------------- */
26.798639
87
0.66759
fa1fba215f6c33fa128baefe70717536f7abb0f7
5,724
c
C
sdk/sdk/share/ffmpeg/libavcodec/arm/rv40dsp_init_neon.c
doyaGu/C0501Q_HWJL01
07a71328bd9038453cbb1cf9c276a3dd1e416d63
[ "MIT" ]
1
2021-10-09T08:05:50.000Z
2021-10-09T08:05:50.000Z
sdk/sdk/share/ffmpeg/libavcodec/arm/rv40dsp_init_neon.c
doyaGu/C0501Q_HWJL01
07a71328bd9038453cbb1cf9c276a3dd1e416d63
[ "MIT" ]
null
null
null
sdk/sdk/share/ffmpeg/libavcodec/arm/rv40dsp_init_neon.c
doyaGu/C0501Q_HWJL01
07a71328bd9038453cbb1cf9c276a3dd1e416d63
[ "MIT" ]
null
null
null
/* * Copyright (c) 2011 Janne Grunau <janne-libav@jannau.net> * * This file is part of Libav. * * Libav is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * Libav is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Libav; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <stdint.h> #include "libavcodec/avcodec.h" #include "libavcodec/rv34dsp.h" #define DECL_QPEL3(type, w, pos) \ void ff_##type##_rv40_qpel##w##_mc##pos##_neon(uint8_t *dst, uint8_t *src,\ int stride) #define DECL_QPEL2(w, pos) \ DECL_QPEL3(put, w, pos); \ DECL_QPEL3(avg, w, pos) #define DECL_QPEL_XY(x, y) \ DECL_QPEL2(16, x ## y); \ DECL_QPEL2(8, x ## y) #define DECL_QPEL_Y(y) \ DECL_QPEL_XY(0, y); \ DECL_QPEL_XY(1, y); \ DECL_QPEL_XY(2, y); \ DECL_QPEL_XY(3, y); \ DECL_QPEL_Y(0); DECL_QPEL_Y(1); DECL_QPEL_Y(2); DECL_QPEL_Y(3); void ff_put_rv40_chroma_mc8_neon(uint8_t *, uint8_t *, int, int, int, int); void ff_put_rv40_chroma_mc4_neon(uint8_t *, uint8_t *, int, int, int, int); void ff_avg_rv40_chroma_mc8_neon(uint8_t *, uint8_t *, int, int, int, int); void ff_avg_rv40_chroma_mc4_neon(uint8_t *, uint8_t *, int, int, int, int); void ff_rv40_weight_func_16_neon(uint8_t *, uint8_t *, uint8_t *, int, int, int); void ff_rv40_weight_func_8_neon(uint8_t *, uint8_t *, uint8_t *, int, int, int); void ff_rv40dsp_init_neon(RV34DSPContext *c, DSPContext* dsp) { c->put_pixels_tab[0][ 1] = ff_put_rv40_qpel16_mc10_neon; c->put_pixels_tab[0][ 3] = ff_put_rv40_qpel16_mc30_neon; c->put_pixels_tab[0][ 4] = ff_put_rv40_qpel16_mc01_neon; c->put_pixels_tab[0][ 5] = ff_put_rv40_qpel16_mc11_neon; c->put_pixels_tab[0][ 6] = ff_put_rv40_qpel16_mc21_neon; c->put_pixels_tab[0][ 7] = ff_put_rv40_qpel16_mc31_neon; c->put_pixels_tab[0][ 9] = ff_put_rv40_qpel16_mc12_neon; c->put_pixels_tab[0][10] = ff_put_rv40_qpel16_mc22_neon; c->put_pixels_tab[0][11] = ff_put_rv40_qpel16_mc32_neon; c->put_pixels_tab[0][12] = ff_put_rv40_qpel16_mc03_neon; c->put_pixels_tab[0][13] = ff_put_rv40_qpel16_mc13_neon; c->put_pixels_tab[0][14] = ff_put_rv40_qpel16_mc23_neon; c->put_pixels_tab[0][15] = ff_put_rv40_qpel16_mc33_neon; c->avg_pixels_tab[0][ 1] = ff_avg_rv40_qpel16_mc10_neon; c->avg_pixels_tab[0][ 3] = ff_avg_rv40_qpel16_mc30_neon; c->avg_pixels_tab[0][ 4] = ff_avg_rv40_qpel16_mc01_neon; c->avg_pixels_tab[0][ 5] = ff_avg_rv40_qpel16_mc11_neon; c->avg_pixels_tab[0][ 6] = ff_avg_rv40_qpel16_mc21_neon; c->avg_pixels_tab[0][ 7] = ff_avg_rv40_qpel16_mc31_neon; c->avg_pixels_tab[0][ 9] = ff_avg_rv40_qpel16_mc12_neon; c->avg_pixels_tab[0][10] = ff_avg_rv40_qpel16_mc22_neon; c->avg_pixels_tab[0][11] = ff_avg_rv40_qpel16_mc32_neon; c->avg_pixels_tab[0][12] = ff_avg_rv40_qpel16_mc03_neon; c->avg_pixels_tab[0][13] = ff_avg_rv40_qpel16_mc13_neon; c->avg_pixels_tab[0][14] = ff_avg_rv40_qpel16_mc23_neon; c->avg_pixels_tab[0][15] = ff_avg_rv40_qpel16_mc33_neon; c->put_pixels_tab[1][ 1] = ff_put_rv40_qpel8_mc10_neon; c->put_pixels_tab[1][ 3] = ff_put_rv40_qpel8_mc30_neon; c->put_pixels_tab[1][ 4] = ff_put_rv40_qpel8_mc01_neon; c->put_pixels_tab[1][ 5] = ff_put_rv40_qpel8_mc11_neon; c->put_pixels_tab[1][ 6] = ff_put_rv40_qpel8_mc21_neon; c->put_pixels_tab[1][ 7] = ff_put_rv40_qpel8_mc31_neon; c->put_pixels_tab[1][ 9] = ff_put_rv40_qpel8_mc12_neon; c->put_pixels_tab[1][10] = ff_put_rv40_qpel8_mc22_neon; c->put_pixels_tab[1][11] = ff_put_rv40_qpel8_mc32_neon; c->put_pixels_tab[1][12] = ff_put_rv40_qpel8_mc03_neon; c->put_pixels_tab[1][13] = ff_put_rv40_qpel8_mc13_neon; c->put_pixels_tab[1][14] = ff_put_rv40_qpel8_mc23_neon; c->put_pixels_tab[1][15] = ff_put_rv40_qpel8_mc33_neon; c->avg_pixels_tab[1][ 1] = ff_avg_rv40_qpel8_mc10_neon; c->avg_pixels_tab[1][ 3] = ff_avg_rv40_qpel8_mc30_neon; c->avg_pixels_tab[1][ 4] = ff_avg_rv40_qpel8_mc01_neon; c->avg_pixels_tab[1][ 5] = ff_avg_rv40_qpel8_mc11_neon; c->avg_pixels_tab[1][ 6] = ff_avg_rv40_qpel8_mc21_neon; c->avg_pixels_tab[1][ 7] = ff_avg_rv40_qpel8_mc31_neon; c->avg_pixels_tab[1][ 9] = ff_avg_rv40_qpel8_mc12_neon; c->avg_pixels_tab[1][10] = ff_avg_rv40_qpel8_mc22_neon; c->avg_pixels_tab[1][11] = ff_avg_rv40_qpel8_mc32_neon; c->avg_pixels_tab[1][12] = ff_avg_rv40_qpel8_mc03_neon; c->avg_pixels_tab[1][13] = ff_avg_rv40_qpel8_mc13_neon; c->avg_pixels_tab[1][14] = ff_avg_rv40_qpel8_mc23_neon; c->avg_pixels_tab[1][15] = ff_avg_rv40_qpel8_mc33_neon; c->put_chroma_pixels_tab[0] = ff_put_rv40_chroma_mc8_neon; c->put_chroma_pixels_tab[1] = ff_put_rv40_chroma_mc4_neon; c->avg_chroma_pixels_tab[0] = ff_avg_rv40_chroma_mc8_neon; c->avg_chroma_pixels_tab[1] = ff_avg_rv40_chroma_mc4_neon; c->rv40_weight_pixels_tab[0] = ff_rv40_weight_func_16_neon; c->rv40_weight_pixels_tab[1] = ff_rv40_weight_func_8_neon; }
47.7
81
0.702655
3663ff2139cdfaa34b74614052225843d22429c4
3,677
h
C
src/ray/raylet/task.h
cumttang/ray
eb1e5fa2cf26233701ccbda3eb8a301ecd418d8c
[ "Apache-2.0" ]
2
2019-10-08T13:31:08.000Z
2019-10-22T18:34:52.000Z
src/ray/raylet/task.h
cumttang/ray
eb1e5fa2cf26233701ccbda3eb8a301ecd418d8c
[ "Apache-2.0" ]
1
2018-12-26T01:09:50.000Z
2018-12-26T01:09:50.000Z
src/ray/raylet/task.h
cumttang/ray
eb1e5fa2cf26233701ccbda3eb8a301ecd418d8c
[ "Apache-2.0" ]
6
2019-03-12T05:37:35.000Z
2020-03-09T12:25:17.000Z
#ifndef RAY_RAYLET_TASK_H #define RAY_RAYLET_TASK_H #include <inttypes.h> #include "ray/raylet/format/node_manager_generated.h" #include "ray/raylet/task_execution_spec.h" #include "ray/raylet/task_spec.h" namespace ray { namespace raylet { /// \class Task /// /// A Task represents a Ray task and a specification of its execution (e.g., /// resource demands). The task's specification contains both immutable fields, /// determined at submission time, and mutable fields, determined at execution /// time. class Task { public: /// Create a task. /// /// \param execution_spec The execution specification for the task. These are /// the mutable fields in the task specification that may change at task /// execution time. /// \param task_spec The immutable specification for the task. These fields /// are determined at task submission time. Task(const TaskExecutionSpecification &execution_spec, const TaskSpecification &task_spec) : task_execution_spec_(execution_spec), task_spec_(task_spec) { ComputeDependencies(); } /// Create a task from a serialized flatbuffer. /// /// \param task_flatbuffer The serialized task. Task(const protocol::Task &task_flatbuffer) : Task(*task_flatbuffer.task_execution_spec(), *task_flatbuffer.task_specification()) {} /// Create a task from a flatbuffer object. /// /// \param task_data The task flatbuffer object. Task(const protocol::TaskT &task_data) : Task(*task_data.task_execution_spec, task_data.task_specification) {} /// Destroy the task. virtual ~Task() {} /// Serialize a task to a flatbuffer. /// /// \param fbb The flatbuffer builder. /// \return An offset to the serialized task. flatbuffers::Offset<protocol::Task> ToFlatbuffer( flatbuffers::FlatBufferBuilder &fbb) const; /// Get the mutable specification for the task. This specification may be /// updated at runtime. /// /// \return The mutable specification for the task. const TaskExecutionSpecification &GetTaskExecutionSpec() const; /// Get the immutable specification for the task. /// /// \return The immutable specification for the task. const TaskSpecification &GetTaskSpecification() const; /// Set the task's execution dependencies. /// /// \param dependencies The value to set the execution dependencies to. void SetExecutionDependencies(const std::vector<ObjectID> &dependencies); /// Increment the number of times this task has been forwarded. void IncrementNumForwards(); /// Get the task's object dependencies. This comprises the immutable task /// arguments and the mutable execution dependencies. /// /// \return The object dependencies. const std::vector<ObjectID> &GetDependencies() const; /// Update the dynamic/mutable information for this task. /// \param task Task structure with updated dynamic information. void CopyTaskExecutionSpec(const Task &task); private: void ComputeDependencies(); /// Task execution specification, consisting of all dynamic/mutable /// information about this task determined at execution time.. TaskExecutionSpecification task_execution_spec_; /// Task specification object, consisting of immutable information about this /// task determined at submission time. Includes resource demand, object /// dependencies, etc. TaskSpecification task_spec_; /// A cached copy of the task's object dependencies, including arguments from /// the TaskSpecification and execution dependencies from the /// TaskExecutionSpecification. std::vector<ObjectID> dependencies_; }; } // namespace raylet } // namespace ray #endif // RAY_RAYLET_TASK_H
34.046296
79
0.735926
d2fcf97f3b92430b855b48ce1e8071bdd8d00e9b
512
c
C
lang/C/read-entire-file-1.c
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
2
2017-06-10T14:21:53.000Z
2017-06-26T18:52:29.000Z
lang/C/read-entire-file-1.c
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
null
null
null
lang/C/read-entire-file-1.c
ethansaxenian/RosettaDecode
8ea1a42a5f792280b50193ad47545d14ee371fb7
[ "MIT" ]
1
2018-11-09T22:08:40.000Z
2018-11-09T22:08:40.000Z
#include <stdio.h> #include <stdlib.h> int main() { char *buffer; FILE *fh = fopen("readentirefile.c", "rb"); if ( fh != NULL ) { fseek(fh, 0L, SEEK_END); long s = ftell(fh); rewind(fh); buffer = malloc(s); if ( buffer != NULL ) { fread(buffer, s, 1, fh); // we can now close the file fclose(fh); fh = NULL; // do something, e.g. fwrite(buffer, s, 1, stdout); free(buffer); } if (fh != NULL) fclose(fh); } return EXIT_SUCCESS; }
17.655172
45
0.523438
d2fee0baf401290e359db28bcf621662956904bd
3,335
h
C
include/atmega644p.h
rolfeb/avr-common
4d16a97566c98954602cfc1194a1fc4c5b8ca338
[ "Unlicense" ]
null
null
null
include/atmega644p.h
rolfeb/avr-common
4d16a97566c98954602cfc1194a1fc4c5b8ca338
[ "Unlicense" ]
null
null
null
include/atmega644p.h
rolfeb/avr-common
4d16a97566c98954602cfc1194a1fc4c5b8ca338
[ "Unlicense" ]
null
null
null
#ifndef __INCLUDE_ATMEGA644P_H #define __INCLUDE_ATMEGA644P_H #include <avr/io.h> #include <avr/interrupt.h> #define ENABLE_EXTERNAL_INT0() \ do { \ /* generate interrupt on falling edge of INT0 */ \ sbi(EICRA, ISC01); \ cbi(EICRA, ISC00); \ \ /* enable interrupts for INT0 */ \ sbi(EIMSK, INT0); \ } while (0) /* * Define parameters for the I2C interface */ #define AVR_I2C_DDR DDRC #define AVR_I2C_PORT PORTC #define AVR_I2C_PORT_SCL PC0 #define AVR_I2C_PORT_SDA PC1 #ifndef AVR_I2C_CLOCK_HZ # define AVR_I2C_CLOCK_HZ 100000L #endif /* * Define parameters for the SPI interface */ #define AVR_SPI_DDR DDRB #define AVR_SPI_PORT PORTB #define AVR_SPI_PORT_SS PB4 #define AVR_SPI_PORT_MOSI PB5 #define AVR_SPI_PORT_MISO PB6 #define AVR_SPI_PORT_SCK PB7 #define AVR_SPI_DATA_REGISTER SPDR #define spi_enable() do { sbi(SPCR, SPE); } while(0) #define spi_write_is_complete() (SPSR & (1<<SPIF)) #define spi_set_master_mode() do { sbi(SPCR, MSTR); } while(0) #define spi_set_speed_osc16() do { sbi(SPCR, SPR0); } while(0) /* * Define parameters for the default UART */ #define UBRR(CPU, BAUD) ((((((CPU) * 10) / (16L * (BAUD))) + 5) / 10) - 1) #define uart0_init(baud) \ do { \ UBRR0H = (UBRR(F_CPU, baud) & 0xff00) >> 8; \ UBRR0L = (UBRR(F_CPU, baud) & 0x00ff); \ \ sbi(UCSR0B, RXEN0); \ sbi(UCSR0B, TXEN0); \ \ UCSR0C = (1<<UCSZ01)|(1<<UCSZ00); \ \ uart0_open_stdout(); \ } while (0) #define uart0_enable_rx_interrupts() \ do { \ sbi(UCSR0B, RXCIE0); \ } while (0) #define AVR_UART0_DATA_REGISTER UDR0 #define AVR_UART0_STATUS_REGISTER UCSR0A #define AVR_UART0_STATUS_REGISTER_DATA_READY_MASK (1<<UDRE0) #define AVR_UART0_STATUS_REGISTER_DATA_SENT_MASK (1<<TXC0) #define AVR_UART0_STATUS_REGISTER_DATA_RECVD_MASK (1<<RXC0) #define uart0_send_byte(C) \ do { \ UCSR0A |= TXC0; \ UDR0 = (C); \ } while (0) #define uart0_tx_buffer_empty() ((UCSR0A & (1<<UDRE0)) != 0) #define uart0_tx_send_complete() ((UCSR0A & (1<<TXC0)) != 0) #define uart0_rx_data_available() ((UCSR0A & (1<<RXC0)) != 0) #define uart0_rx_error() ((UCSR0A & ((1<<FE0)|(1<<DOR0)|(1<<UPE0))) != 0) #endif /* __INCLUDE_ATMEGA644P_H */
34.739583
76
0.448876
d0a226d07706f9aa5ac16e71e33622e613b1cd2b
1,142
h
C
lib/include/performance_api.h
PokemonWei/multi-master-sqlite
1921bb695766a2aca0abf2234bed3c51b89820e3
[ "MIT" ]
1
2019-12-29T11:23:19.000Z
2019-12-29T11:23:19.000Z
lib/include/performance_api.h
PokemonWei/multi-master-sqlite
1921bb695766a2aca0abf2234bed3c51b89820e3
[ "MIT" ]
5
2019-07-25T00:18:33.000Z
2019-08-20T02:56:13.000Z
lib/include/performance_api.h
PokemonWei/multi-master-sqlite
1921bb695766a2aca0abf2234bed3c51b89820e3
[ "MIT" ]
null
null
null
#ifndef PERFORMANCE_INCLUDE #define PERFORMANCE_INCLUDE #include <stdint.h> /** * Type of performance indicatior value */ #define VALUE_TYPE int64_t //performance record type #define PERFORMANCE_TIME 1 //============================================================ /*** * Performance API **/ #ifdef __cplusplus void createIndicatior(const char * dirPath,const char * name); long long beginIndicatiorTimeRecord(const char * name); long long endIndicatiorTimeRecord(const char * name); void addPerformanceRecord(const char * name,VALUE_TYPE val); void flushNow(const char * name); void finishRecord(const char * name); #endif #ifdef __cplusplus extern "C"{ #endif void createIndicatior_C_API(const char * dirPath,const char * name); long long beginIndicatiorTimeRecord_C_API(const char * name); long long endIndicatiorTimeRecord_C_API(const char * name); void addPerformanceRecord_C_API(const char * name,VALUE_TYPE val); void flushNow_C_API(const char * name); void finishRecord_C_API(const char * name); #ifdef __cplusplus } #endif //============================================================ #endif // PERFORMANCE_INCLUDE
24.297872
68
0.694396
fde03c3b3a4bca0f704d9354a84a7f4eb8806e3c
447
h
C
src/error.h
feniksa/mojoview
031fb4eed356c6590fbfe2bde5309de941dd31c0
[ "Apache-2.0" ]
null
null
null
src/error.h
feniksa/mojoview
031fb4eed356c6590fbfe2bde5309de941dd31c0
[ "Apache-2.0" ]
null
null
null
src/error.h
feniksa/mojoview
031fb4eed356c6590fbfe2bde5309de941dd31c0
[ "Apache-2.0" ]
null
null
null
#ifndef ERROR_H #define ERROR_H #include <QString> #include <QDebug> #include <exception> namespace tabor { class Error : public std::exception { public: Error(const QString& _reason) throw(); ~Error() throw(); virtual const char* what() const throw(); inline const QString& getReason() const throw() { return reason; } private: QString reason; }; QDebug operator<<(QDebug dbg, const Error &error); } #endif
14.9
53
0.666667
a94bc65effdea0c55b08f273e20d86911aa0dee5
4,070
c
C
Microsoft Word for Windows Version 1.1a/Word 1.1a CHM Distribution/Opus/elxprocs.c
lborgav/Historical-Source-Codes
c0aeaae1d482718e3b469d9eb7a6d0002faa1ff5
[ "MIT" ]
7
2017-01-12T17:48:48.000Z
2021-11-28T04:37:34.000Z
Microsoft Word for Windows Version 1.1a/Word 1.1a CHM Distribution/Opus/elxprocs.c
lborgav/Historical-Source-Codes
c0aeaae1d482718e3b469d9eb7a6d0002faa1ff5
[ "MIT" ]
null
null
null
Microsoft Word for Windows Version 1.1a/Word 1.1a CHM Distribution/Opus/elxprocs.c
lborgav/Historical-Source-Codes
c0aeaae1d482718e3b469d9eb7a6d0002faa1ff5
[ "MIT" ]
5
2017-03-28T08:04:30.000Z
2020-03-25T14:25:29.000Z
/* elxprocs.c: This file contains procedures which access the dialog * information which the EB system needs. * * "#include" this file in an application module, after #include'ing either: * ELXDEFS.H and ELXINFO.H (generated by the MAKEELX utility) * or * ELXDEFS0.H and ELXINFO0.H (stubs for temporary use) * */ /* %%Function:GetNameElk %%Owner:bradch */ VOID GetNameElk(elk, st) /* Accepts an ELK; produces the name associated with the ELK. */ ELK elk; unsigned char *st; { char far *lst; if (elk >= elkAppMac) { extern struct STTB ** vhsttbElkUser; char * stT; /* user defined keyword, load from vhsttbElkUser */ elk -= elkAppMac; Assert(vhsttbElkUser != hNil); Assert(elk < (*vhsttbElkUser)->ibstMac); BLTB(stT = PstFromSttb(vhsttbElkUser, elk), st, *stT + 1); } else { lst = &rgchElkNames[rgichName[mpelkistName[elk]]]; BLTBX(lst, (char far *)st, lst[0] + 1); } } /* %%Function:ElkLookupSt %%Owner:bradch */ NATIVE ELX ElkLookupSt(st) /* Accepts a near pointer to a string; returns the ELK named by the string, * or elxNil if there is no such ELK. * * The current lookup algorithm is a binary search. If desired, this may * change to a more time-efficient algorithm. * * Made native for optimizing macro tokenization. */ unsigned char *st; { int istFirst, istLast; /* Look for the name in the hash table, or the position where it * should be. */ istFirst = 0; istLast = ibstElkAppMac; while (istFirst < istLast) { int istMid = (istFirst + istLast) / 2; int wDiff; wDiff = WCmpiStLst(st, &rgchElkNames[rgichName[istMid]]); if (wDiff < 0) istLast = istMid; /* table entry too high */ else if (wDiff > 0) istFirst = istMid + 1; /* table entry too low */ else { return ElkFromIstElk(istMid); /* found */ } } return elkNil; /* not found */ } /* %%Function:ElkFromIstElk %%Owner:bradch */ ElkFromIstElk(istElk) int istElk; { int far * pist; for (pist = mpelkistName; *pist != istElk; pist += 1) /*Assert(pist < (char *) mpelkistName + sizeof (mpelkistName))*/; return (int) (pist - mpelkistName); } /* %%Function:HidFromIeldi %%Owner:bradch */ WORD HidFromIeldi(ieldi) int ieldi; { return rgeldi[ieldi].hid; } /* %%Function:CbGetInfoIeldi %%Owner:bradch */ WORD CbGetInfoIeldi(ieldi, hpeldi) /* Locates an ELDI structure and returns its size. If "hpeldi" != hpNil, * copies the ELDI there. */ int ieldi; ELDI huge *hpeldi; { extern ELDI ** vheldi; ELDI far * lpeldi; unsigned cb; lpeldi = (ieldi == ieldiIDDUsrDlg) ? (ELDI far *) *vheldi : &rgeldi[ieldi]; cb = CbEldiOfCelfd(lpeldi->celfd); if (hpeldi != hpNil) { BLTBX(lpeldi, LpOfHp(hpeldi), cb); } return cb; } /* ---------------------------------------------------------------------- */ /* Utility functions /* ---------------------------------------------------------------------- */ /* %%Function:WCmpiStLst %%Owner:bradch */ int WCmpiStLst(st1, lst2) /* Compares two counted character strings. This function must be in the same * module as "ElxLookupSt()" (so a code-space pointer can be passed). */ unsigned char *st1, far *lst2; { unsigned cch1, cch2; cch1 = *st1++; cch2 = *lst2++; while (cch1 != 0 && cch2 != 0) { unsigned char ch1 = *st1++, ch2 = *lst2++; if (ch1 != ch2) { ch1 |= 0x20; ch2 |= 0x20; if (!(ch1 == ch2 && ch1 >= 'a' && ch1 <= 'z')) return ch1 - ch2; } cch1--; cch2--; } return cch1 - cch2; } /* FUTURE: mergeelx needs to spit this out */ #ifdef DEBUG #define ieldiMax (ieldiIDDUseCThreeVersions + 1) #else #define ieldiMax (ieldiIDDUsrDlg + 1) #endif /* FUTURE: This sucks! Should be direct mapping from hid to ieldi! */ /* %%Function:IeldiFromHid %%Owner:bradch */ int IeldiFromHid(hid) WORD hid; { int ieldi; for (ieldi = 0; ieldi < ieldiMax; ++ieldi) { if (rgeldi[ieldi].hid == hid) { return ieldi; } } return iNil; }
21.88172
78
0.599509
04b339373172cbb323268044c16f62f4ab8cfaeb
703
h
C
External/Quiver/Source/Quiver/Quiver/Application/Application.h
rachelnertia/Quarrel
69616179fc71305757549c7fcaccc22707a91ba4
[ "MIT" ]
39
2017-10-22T15:47:39.000Z
2020-03-31T22:19:55.000Z
External/Quiver/Source/Quiver/Quiver/Application/Application.h
rachelnertia/Quarrel
69616179fc71305757549c7fcaccc22707a91ba4
[ "MIT" ]
46
2017-10-26T21:21:51.000Z
2018-10-13T14:46:17.000Z
Source/Quiver/Quiver/Application/Application.h
rachelnertia/Quiver
c8ef9591117bdfc8d6fa509ae53451e0807f5686
[ "MIT" ]
8
2017-10-22T14:47:57.000Z
2020-03-19T10:08:45.000Z
#pragma once #include <memory> #include "Quiver/Physics/PhysicsUtils.h" namespace sf { class RenderWindow; } namespace qvr { class ApplicationStateLibrary; class CustomComponentTypeLibrary; struct ApplicationConfig; struct ApplicationParams; struct ApplicationParams { CustomComponentTypeLibrary& customComponentTypes; FixtureFilterBitNames& fixtureFilterBitNames; ApplicationConfig& config; ApplicationStateLibrary& userStates; }; int RunApplication(ApplicationParams params); int RunApplication( CustomComponentTypeLibrary& customComponentTypes, FixtureFilterBitNames& fixtureFilterBitNames); int RunApplication(CustomComponentTypeLibrary& customComponentTypes); int RunApplication(); }
21.96875
69
0.843528
aa9c2cdf7a83b5a82bcf85c0b62f78ee112463d1
34,001
c
C
ShellPkg/DynamicCommand/DpDynamicCommand/Dp.c
CEOALT1/RefindPlusUDK
116b957ad735f96fbb6d80a0ba582046960ba164
[ "BSD-2-Clause" ]
3,861
2019-09-04T10:10:11.000Z
2022-03-31T15:46:28.000Z
ShellPkg/DynamicCommand/DpDynamicCommand/Dp.c
CEOALT1/RefindPlusUDK
116b957ad735f96fbb6d80a0ba582046960ba164
[ "BSD-2-Clause" ]
461
2019-09-24T10:26:56.000Z
2022-03-26T13:22:32.000Z
ShellPkg/DynamicCommand/DpDynamicCommand/Dp.c
CEOALT1/RefindPlusUDK
116b957ad735f96fbb6d80a0ba582046960ba164
[ "BSD-2-Clause" ]
654
2019-09-05T11:42:37.000Z
2022-03-30T02:42:32.000Z
/** @file Shell command for Displaying Performance Metrics. The Dp command reads performance data and presents it in several different formats depending upon the needs of the user. Both Trace and Measured Profiling information is processed and presented. Dp uses the "PerformanceLib" to read the measurement records. The "TimerLib" provides information about the timer, such as frequency, beginning, and ending counter values. Measurement records contain identifying information (Handle, Token, Module) and start and end time values. Dp uses this information to group records in different ways. It also uses timer information to calculate elapsed time for each measurement. Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved. (C) Copyright 2015-2016 Hewlett Packard Enterprise Development LP<BR> This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ #include "Dp.h" #include "Literals.h" #include "DpInternal.h" #pragma pack(1) typedef struct { EFI_ACPI_DESCRIPTION_HEADER Header; UINT32 Entry; } RSDT_TABLE; typedef struct { EFI_ACPI_DESCRIPTION_HEADER Header; UINT64 Entry; } XSDT_TABLE; #pragma pack() EFI_HANDLE mDpHiiHandle; typedef struct { EFI_HANDLE Handle; EFI_GUID ModuleGuid; } HANDLE_GUID_MAP; HANDLE_GUID_MAP *mCacheHandleGuidTable; UINTN mCachePairCount = 0; // /// Module-Global Variables ///@{ CHAR16 mGaugeString[DP_GAUGE_STRING_LENGTH + 1]; CHAR16 mUnicodeToken[DXE_PERFORMANCE_STRING_SIZE]; UINT64 mInterestThreshold; BOOLEAN mShowId = FALSE; UINT8 *mBootPerformanceTable; UINTN mBootPerformanceTableSize; BOOLEAN mPeiPhase = FALSE; BOOLEAN mDxePhase = FALSE; PERF_SUMMARY_DATA SummaryData = { 0 }; ///< Create the SummaryData structure and init. to ZERO. MEASUREMENT_RECORD *mMeasurementList = NULL; UINTN mMeasurementNum = 0; /// Items for which to gather cumulative statistics. PERF_CUM_DATA CumData[] = { PERF_INIT_CUM_DATA (LOAD_IMAGE_TOK), PERF_INIT_CUM_DATA (START_IMAGE_TOK), PERF_INIT_CUM_DATA (DRIVERBINDING_START_TOK), PERF_INIT_CUM_DATA (DRIVERBINDING_SUPPORT_TOK) }; /// Number of items for which we are gathering cumulative statistics. UINT32 const NumCum = sizeof(CumData) / sizeof(PERF_CUM_DATA); STATIC CONST SHELL_PARAM_ITEM ParamList[] = { {L"-v", TypeFlag}, // -v Verbose Mode {L"-A", TypeFlag}, // -A All, Cooked {L"-R", TypeFlag}, // -R RAW All {L"-s", TypeFlag}, // -s Summary #if PROFILING_IMPLEMENTED {L"-P", TypeFlag}, // -P Dump Profile Data {L"-T", TypeFlag}, // -T Dump Trace Data #endif // PROFILING_IMPLEMENTED {L"-x", TypeFlag}, // -x eXclude Cumulative Items {L"-i", TypeFlag}, // -i Display Identifier {L"-c", TypeValue}, // -c Display cumulative data. {L"-n", TypeValue}, // -n # Number of records to display for A and R {L"-t", TypeValue}, // -t # Threshold of interest {NULL, TypeMax} }; ///@} /** Display the trailing Verbose information. **/ VOID DumpStatistics( void ) { EFI_STRING StringPtr; EFI_STRING StringPtrUnknown; StringPtr = HiiGetString (mDpHiiHandle, STRING_TOKEN (STR_DP_SECTION_STATISTICS), NULL); StringPtrUnknown = HiiGetString (mDpHiiHandle, STRING_TOKEN (STR_ALIT_UNKNOWN), NULL); ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_DP_SECTION_HEADER), mDpHiiHandle, (StringPtr == NULL) ? StringPtrUnknown : StringPtr); ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_DP_STATS_NUMTRACE), mDpHiiHandle, SummaryData.NumTrace); ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_DP_STATS_NUMINCOMPLETE), mDpHiiHandle, SummaryData.NumIncomplete); ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_DP_STATS_NUMPHASES), mDpHiiHandle, SummaryData.NumSummary); ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_DP_STATS_NUMHANDLES), mDpHiiHandle, SummaryData.NumHandles, SummaryData.NumTrace - SummaryData.NumHandles); ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_DP_STATS_NUMPEIMS), mDpHiiHandle, SummaryData.NumPEIMs); ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_DP_STATS_NUMGLOBALS), mDpHiiHandle, SummaryData.NumGlobal); #if PROFILING_IMPLEMENTED ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_DP_STATS_NUMPROFILE), mDpHiiHandle, SummaryData.NumProfile); #endif // PROFILING_IMPLEMENTED SHELL_FREE_NON_NULL (StringPtr); SHELL_FREE_NON_NULL (StringPtrUnknown); } /** This function scan ACPI table in RSDT. @param Rsdt ACPI RSDT @param Signature ACPI table signature @return ACPI table **/ VOID * ScanTableInRSDT ( IN RSDT_TABLE *Rsdt, IN UINT32 Signature ) { UINTN Index; UINT32 EntryCount; UINT32 *EntryPtr; EFI_ACPI_DESCRIPTION_HEADER *Table; EntryCount = (Rsdt->Header.Length - sizeof (EFI_ACPI_DESCRIPTION_HEADER)) / sizeof(UINT32); EntryPtr = &Rsdt->Entry; for (Index = 0; Index < EntryCount; Index ++, EntryPtr ++) { Table = (EFI_ACPI_DESCRIPTION_HEADER*)((UINTN)(*EntryPtr)); if (Table->Signature == Signature) { return Table; } } return NULL; } /** This function scan ACPI table in XSDT. @param Xsdt ACPI XSDT @param Signature ACPI table signature @return ACPI table **/ VOID * ScanTableInXSDT ( IN XSDT_TABLE *Xsdt, IN UINT32 Signature ) { UINTN Index; UINT32 EntryCount; UINT64 EntryPtr; UINTN BasePtr; EFI_ACPI_DESCRIPTION_HEADER *Table; EntryCount = (Xsdt->Header.Length - sizeof (EFI_ACPI_DESCRIPTION_HEADER)) / sizeof(UINT64); BasePtr = (UINTN)(&(Xsdt->Entry)); for (Index = 0; Index < EntryCount; Index ++) { CopyMem (&EntryPtr, (VOID *)(BasePtr + Index * sizeof(UINT64)), sizeof(UINT64)); Table = (EFI_ACPI_DESCRIPTION_HEADER*)((UINTN)(EntryPtr)); if (Table->Signature == Signature) { return Table; } } return NULL; } /** This function scan ACPI table in RSDP. @param Rsdp ACPI RSDP @param Signature ACPI table signature @return ACPI table **/ VOID * FindAcpiPtr ( IN EFI_ACPI_5_0_ROOT_SYSTEM_DESCRIPTION_POINTER *Rsdp, IN UINT32 Signature ) { EFI_ACPI_DESCRIPTION_HEADER *AcpiTable; RSDT_TABLE *Rsdt; XSDT_TABLE *Xsdt; AcpiTable = NULL; // // Check ACPI2.0 table // Rsdt = (RSDT_TABLE *)(UINTN)Rsdp->RsdtAddress; Xsdt = NULL; if ((Rsdp->Revision >= 2) && (Rsdp->XsdtAddress < (UINT64)(UINTN)-1)) { Xsdt = (XSDT_TABLE *)(UINTN)Rsdp->XsdtAddress; } // // Check Xsdt // if (Xsdt != NULL) { AcpiTable = ScanTableInXSDT (Xsdt, Signature); } // // Check Rsdt // if ((AcpiTable == NULL) && (Rsdt != NULL)) { AcpiTable = ScanTableInRSDT (Rsdt, Signature); } return AcpiTable; } /** Get Boot performance table form Acpi table. **/ EFI_STATUS GetBootPerformanceTable ( ) { EFI_STATUS Status; VOID *AcpiTable; FIRMWARE_PERFORMANCE_TABLE *FirmwarePerformanceTable; AcpiTable = NULL; Status = EfiGetSystemConfigurationTable ( &gEfiAcpi20TableGuid, &AcpiTable ); if (EFI_ERROR (Status)) { Status = EfiGetSystemConfigurationTable ( &gEfiAcpi10TableGuid, &AcpiTable ); } if (EFI_ERROR(Status) || AcpiTable == NULL) { ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_DP_GET_ACPI_TABLE_FAIL), mDpHiiHandle); return Status; } FirmwarePerformanceTable = FindAcpiPtr ( (EFI_ACPI_5_0_ROOT_SYSTEM_DESCRIPTION_POINTER *)AcpiTable, EFI_ACPI_5_0_FIRMWARE_PERFORMANCE_DATA_TABLE_SIGNATURE ); if (FirmwarePerformanceTable == NULL) { ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_DP_GET_ACPI_FPDT_FAIL), mDpHiiHandle); return EFI_NOT_FOUND; } mBootPerformanceTable = (UINT8*) (UINTN)FirmwarePerformanceTable->BootPointerRecord.BootPerformanceTablePointer; mBootPerformanceTableSize = ((BOOT_PERFORMANCE_TABLE *) mBootPerformanceTable)->Header.Length; return EFI_SUCCESS; } /** Get Handle form Module Guid. @param ModuleGuid Module Guid. @param Handle The handle to be returned. **/ VOID GetHandleFormModuleGuid ( IN EFI_GUID *ModuleGuid, IN OUT EFI_HANDLE *Handle ) { UINTN Index; if (IsZeroGuid (ModuleGuid)) { *Handle = NULL; } // // Try to get the Handle form the caached array. // for (Index = 0; Index < mCachePairCount; Index++) { if (CompareGuid (ModuleGuid, &mCacheHandleGuidTable[Index].ModuleGuid)) { *Handle = mCacheHandleGuidTable[Index].Handle; break; } } if (Index >= mCachePairCount) { *Handle = NULL; } } /** Cache the GUID and handle mapping pairs. In order to save time for searching. **/ EFI_STATUS BuildCachedGuidHandleTable ( VOID ) { EFI_STATUS Status; EFI_HANDLE *HandleBuffer; UINTN HandleCount; UINTN Index; EFI_LOADED_IMAGE_PROTOCOL *LoadedImage; EFI_DRIVER_BINDING_PROTOCOL *DriverBinding; EFI_GUID *TempGuid; MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *FvFilePath; Status = gBS->LocateHandleBuffer (AllHandles, NULL, NULL, &HandleCount, &HandleBuffer); if (EFI_ERROR (Status)) { ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_DP_HANDLES_ERROR), mDpHiiHandle, Status); return Status; } mCacheHandleGuidTable = AllocateZeroPool (HandleCount * sizeof (HANDLE_GUID_MAP)); if (mCacheHandleGuidTable == NULL) { return EFI_OUT_OF_RESOURCES; } for (Index = 0; Index < HandleCount; Index++) { // // Try Handle as ImageHandle. // Status = gBS->HandleProtocol ( HandleBuffer[Index], &gEfiLoadedImageProtocolGuid, (VOID**) &LoadedImage ); if (EFI_ERROR (Status)) { // // Try Handle as Controller Handle // Status = gBS->OpenProtocol ( HandleBuffer[Index], &gEfiDriverBindingProtocolGuid, (VOID **) &DriverBinding, NULL, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL ); if (!EFI_ERROR (Status)) { // // Get Image protocol from ImageHandle // Status = gBS->HandleProtocol ( DriverBinding->ImageHandle, &gEfiLoadedImageProtocolGuid, (VOID**) &LoadedImage ); } } if (!EFI_ERROR (Status) && LoadedImage != NULL) { // // Get Module Guid from DevicePath. // if (LoadedImage->FilePath != NULL && LoadedImage->FilePath->Type == MEDIA_DEVICE_PATH && LoadedImage->FilePath->SubType == MEDIA_PIWG_FW_FILE_DP ) { FvFilePath = (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) LoadedImage->FilePath; TempGuid = &FvFilePath->FvFileName; mCacheHandleGuidTable[mCachePairCount].Handle = HandleBuffer[Index]; CopyGuid (&mCacheHandleGuidTable[mCachePairCount].ModuleGuid, TempGuid); mCachePairCount ++; } } } if (HandleBuffer != NULL) { FreePool (HandleBuffer); HandleBuffer = NULL; } return Status; } /** Get Measurement form Fpdt records. @param RecordHeader Pointer to the start record. @param IsStart Is start record or End record. @param Measurement Pointer to the measurement which need to be filled. **/ VOID GetMeasurementInfo ( IN EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *RecordHeader, IN BOOLEAN IsStart, IN OUT MEASUREMENT_RECORD *Measurement ) { VOID *ModuleGuid; EFI_HANDLE StartHandle; switch (RecordHeader->Type) { case FPDT_GUID_EVENT_TYPE: ModuleGuid = &(((FPDT_GUID_EVENT_RECORD *)RecordHeader)->Guid); Measurement->Identifier = ((UINT32)((FPDT_GUID_EVENT_RECORD *)RecordHeader)->ProgressID); if (IsStart) { Measurement->StartTimeStamp = ((FPDT_GUID_EVENT_RECORD *)RecordHeader)->Timestamp; } else { Measurement->EndTimeStamp = ((FPDT_GUID_EVENT_RECORD *)RecordHeader)->Timestamp; } switch (Measurement->Identifier) { case MODULE_START_ID: case MODULE_END_ID: if (mPeiPhase) { Measurement->Token = ALit_PEIM; Measurement->Module = ALit_PEIM; } else if (mDxePhase) { Measurement->Token = ALit_START_IMAGE; Measurement->Module = ALit_START_IMAGE; } break; default: ASSERT(FALSE); } if (AsciiStrCmp (Measurement->Token, ALit_PEIM) == 0) { Measurement->Handle = &(((FPDT_GUID_EVENT_RECORD *)RecordHeader)->Guid); } else { GetHandleFormModuleGuid(ModuleGuid, &StartHandle); Measurement->Handle = StartHandle; } break; case FPDT_DYNAMIC_STRING_EVENT_TYPE: ModuleGuid = &(((FPDT_DYNAMIC_STRING_EVENT_RECORD *)RecordHeader)->Guid); Measurement->Identifier = ((UINT32)((FPDT_DYNAMIC_STRING_EVENT_RECORD *)RecordHeader)->ProgressID); if (IsStart) { Measurement->StartTimeStamp = ((FPDT_DYNAMIC_STRING_EVENT_RECORD *)RecordHeader)->Timestamp; } else { Measurement->EndTimeStamp = ((FPDT_DYNAMIC_STRING_EVENT_RECORD *)RecordHeader)->Timestamp; } switch (Measurement->Identifier) { case MODULE_START_ID: case MODULE_END_ID: if (mPeiPhase) { Measurement->Token = ALit_PEIM; } else if (mDxePhase) { Measurement->Token = ALit_START_IMAGE; } break; case MODULE_LOADIMAGE_START_ID: case MODULE_LOADIMAGE_END_ID: Measurement->Token = ALit_LOAD_IMAGE; break; case MODULE_DB_START_ID: case MODULE_DB_END_ID: Measurement->Token = ALit_DB_START; break; case MODULE_DB_SUPPORT_START_ID: case MODULE_DB_SUPPORT_END_ID: Measurement->Token = ALit_DB_SUPPORT; break; case MODULE_DB_STOP_START_ID: case MODULE_DB_STOP_END_ID: Measurement->Token = ALit_DB_STOP; break; default: Measurement->Token = ((FPDT_DYNAMIC_STRING_EVENT_RECORD *)RecordHeader)->String; break; } Measurement->Module = ((FPDT_DYNAMIC_STRING_EVENT_RECORD *)RecordHeader)->String; if (AsciiStrCmp (Measurement->Token, ALit_PEIM) == 0) { Measurement->Handle = &(((FPDT_DYNAMIC_STRING_EVENT_RECORD *)RecordHeader)->Guid); } else { GetHandleFormModuleGuid(ModuleGuid, &StartHandle); Measurement->Handle = StartHandle; } break; case FPDT_GUID_QWORD_EVENT_TYPE: ModuleGuid = &(((FPDT_GUID_QWORD_EVENT_RECORD *)RecordHeader)->Guid); Measurement->Identifier = ((UINT32)((FPDT_GUID_QWORD_EVENT_RECORD *)RecordHeader)->ProgressID); if (IsStart) { Measurement->StartTimeStamp = ((FPDT_GUID_QWORD_EVENT_RECORD *)RecordHeader)->Timestamp; } else { Measurement->EndTimeStamp = ((FPDT_GUID_QWORD_EVENT_RECORD *)RecordHeader)->Timestamp; } switch (Measurement->Identifier) { case MODULE_DB_START_ID: Measurement->Token = ALit_DB_START; Measurement->Module = ALit_DB_START; break; case MODULE_DB_SUPPORT_START_ID: case MODULE_DB_SUPPORT_END_ID: Measurement->Token = ALit_DB_SUPPORT; Measurement->Module = ALit_DB_SUPPORT; break; case MODULE_DB_STOP_START_ID: case MODULE_DB_STOP_END_ID: Measurement->Token = ALit_DB_STOP; Measurement->Module = ALit_DB_STOP; break; case MODULE_LOADIMAGE_START_ID: case MODULE_LOADIMAGE_END_ID: Measurement->Token = ALit_LOAD_IMAGE; Measurement->Module = ALit_LOAD_IMAGE; break; default: ASSERT(FALSE); } GetHandleFormModuleGuid(ModuleGuid, &StartHandle); Measurement->Handle = StartHandle; break; case FPDT_GUID_QWORD_STRING_EVENT_TYPE: ModuleGuid = &(((FPDT_GUID_QWORD_STRING_EVENT_RECORD *)RecordHeader)->Guid); Measurement->Identifier = ((UINT32)((FPDT_GUID_QWORD_STRING_EVENT_RECORD *)RecordHeader)->ProgressID); if (IsStart) { Measurement->StartTimeStamp = ((FPDT_GUID_QWORD_STRING_EVENT_RECORD*)RecordHeader)->Timestamp; } else { Measurement->EndTimeStamp = ((FPDT_GUID_QWORD_STRING_EVENT_RECORD *)RecordHeader)->Timestamp; } // // Currently only "DB:Start:" end record with FPDT_GUID_QWORD_STRING_EVENT_TYPE. // switch (Measurement->Identifier) { case MODULE_DB_END_ID: Measurement->Token = ALit_DB_START; Measurement->Module = ALit_DB_START; break; default: ASSERT(FALSE); } GetHandleFormModuleGuid(ModuleGuid, &StartHandle); Measurement->Handle = StartHandle; break; default: break; } } /** Search the start measurement in the mMeasurementList for the end measurement. @param EndMeasureMent Measurement for end record. **/ VOID SearchMeasurement ( IN MEASUREMENT_RECORD *EndMeasureMent ) { INTN Index; for (Index = mMeasurementNum - 1; Index >= 0; Index--) { if (AsciiStrCmp (EndMeasureMent->Token, ALit_PEIM) == 0) { if (mMeasurementList[Index].EndTimeStamp == 0 && EndMeasureMent->Handle!= NULL && mMeasurementList[Index].Handle != NULL&& CompareGuid(mMeasurementList[Index].Handle, EndMeasureMent->Handle) && (AsciiStrCmp (mMeasurementList[Index].Token, EndMeasureMent->Token) == 0) && (AsciiStrCmp (mMeasurementList[Index].Module, EndMeasureMent->Module) == 0)) { mMeasurementList[Index].EndTimeStamp = EndMeasureMent->EndTimeStamp; break; } } else { if (mMeasurementList[Index].EndTimeStamp == 0 && mMeasurementList[Index].Handle == EndMeasureMent->Handle && (AsciiStrCmp (mMeasurementList[Index].Token, EndMeasureMent->Token) == 0) && (AsciiStrCmp (mMeasurementList[Index].Module, EndMeasureMent->Module) == 0)) { mMeasurementList[Index].EndTimeStamp = EndMeasureMent->EndTimeStamp; break; } } } } /** Generate the measure record array. **/ EFI_STATUS BuildMeasurementList ( ) { EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER *RecordHeader; UINT8 *PerformanceTablePtr; UINT16 StartProgressId; UINTN TableLength; UINT8 *StartRecordEvent; MEASUREMENT_RECORD MeasureMent; mMeasurementList = AllocateZeroPool (mBootPerformanceTableSize); if (mMeasurementList == NULL) { return EFI_OUT_OF_RESOURCES; } TableLength = sizeof (BOOT_PERFORMANCE_TABLE); PerformanceTablePtr = (mBootPerformanceTable + TableLength); while (TableLength < mBootPerformanceTableSize) { RecordHeader = (EFI_ACPI_5_0_FPDT_PERFORMANCE_RECORD_HEADER*) PerformanceTablePtr; StartRecordEvent = (UINT8 *)RecordHeader; StartProgressId = ((FPDT_GUID_EVENT_RECORD *)StartRecordEvent)->ProgressID; // // If the record is the start record, fill the info to the measurement in the mMeasurementList. // If the record is the end record, find the related start measurement in the mMeasurementList and fill the EndTimeStamp. // if (((StartProgressId >= PERF_EVENTSIGNAL_START_ID && ((StartProgressId & 0x000F) == 0)) || (StartProgressId < PERF_EVENTSIGNAL_START_ID && ((StartProgressId & 0x0001) != 0)))) { // // Since PEIM and StartImage has same Type and ID when PCD PcdEdkiiFpdtStringRecordEnableOnly = FALSE // So we need to identify these two kinds of record through different phase. // if (AsciiStrCmp (((FPDT_DYNAMIC_STRING_EVENT_RECORD *)StartRecordEvent)->String, ALit_PEI) == 0) { mPeiPhase = TRUE; } else if (AsciiStrCmp (((FPDT_DYNAMIC_STRING_EVENT_RECORD *)StartRecordEvent)->String, ALit_DXE) == 0) { mDxePhase = TRUE; mPeiPhase = FALSE; } // Get measurement info form the start record to the mMeasurementList. GetMeasurementInfo (RecordHeader, TRUE, &(mMeasurementList[mMeasurementNum])); mMeasurementNum ++; } else { GetMeasurementInfo (RecordHeader, FALSE, &MeasureMent); SearchMeasurement (&MeasureMent); } TableLength += RecordHeader->Length; PerformanceTablePtr += RecordHeader->Length; } return EFI_SUCCESS; } /** Initialize the cumulative data. **/ VOID InitCumulativeData ( VOID ) { UINTN Index; for (Index = 0; Index < NumCum; ++Index) { CumData[Index].Count = 0; CumData[Index].MinDur = PERF_MAXDUR; CumData[Index].MaxDur = 0; CumData[Index].Duration = 0; } } /** Dump performance data. @param[in] ImageHandle The image handle. @param[in] SystemTable The system table. @retval SHELL_SUCCESS Command completed successfully. @retval SHELL_INVALID_PARAMETER Command usage error. @retval SHELL_ABORTED The user aborts the operation. @retval value Unknown error. **/ SHELL_STATUS RunDp ( IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable ) { LIST_ENTRY *ParamPackage; CONST CHAR16 *CmdLineArg; EFI_STATUS Status; PERFORMANCE_PROPERTY *PerformanceProperty; UINTN Number2Display; EFI_STRING StringPtr; BOOLEAN SummaryMode; BOOLEAN VerboseMode; BOOLEAN AllMode; BOOLEAN RawMode; BOOLEAN TraceMode; BOOLEAN ProfileMode; BOOLEAN ExcludeMode; BOOLEAN CumulativeMode; CONST CHAR16 *CustomCumulativeToken; PERF_CUM_DATA *CustomCumulativeData; UINTN NameSize; SHELL_STATUS ShellStatus; TIMER_INFO TimerInfo; StringPtr = NULL; SummaryMode = FALSE; VerboseMode = FALSE; AllMode = FALSE; RawMode = FALSE; TraceMode = FALSE; ProfileMode = FALSE; ExcludeMode = FALSE; CumulativeMode = FALSE; CustomCumulativeData = NULL; ShellStatus = SHELL_SUCCESS; // // initialize the shell lib (we must be in non-auto-init...) // Status = ShellInitialize(); ASSERT_EFI_ERROR(Status); // // DP dump performance data by parsing FPDT table in ACPI table. // Folloing 3 steps are to get the measurement form the FPDT table. // // //1. Get FPDT from ACPI table. // Status = GetBootPerformanceTable (); if (EFI_ERROR(Status)) { return Status; } // //2. Cache the ModuleGuid and hanlde mapping table. // Status = BuildCachedGuidHandleTable(); if (EFI_ERROR (Status)) { return Status; } // //3. Build the measurement array form the FPDT records. // Status = BuildMeasurementList (); if (EFI_ERROR(Status)) { return Status; } // // Process Command Line arguments // Status = ShellCommandLineParse (ParamList, &ParamPackage, NULL, TRUE); if (EFI_ERROR(Status)) { ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_DP_INVALID_ARG), mDpHiiHandle); return SHELL_INVALID_PARAMETER; } // // Boolean options // VerboseMode = ShellCommandLineGetFlag (ParamPackage, L"-v"); SummaryMode = (BOOLEAN) (ShellCommandLineGetFlag (ParamPackage, L"-S") || ShellCommandLineGetFlag (ParamPackage, L"-s")); AllMode = ShellCommandLineGetFlag (ParamPackage, L"-A"); RawMode = ShellCommandLineGetFlag (ParamPackage, L"-R"); #if PROFILING_IMPLEMENTED TraceMode = ShellCommandLineGetFlag (ParamPackage, L"-T"); ProfileMode = ShellCommandLineGetFlag (ParamPackage, L"-P"); #endif // PROFILING_IMPLEMENTED ExcludeMode = ShellCommandLineGetFlag (ParamPackage, L"-x"); mShowId = ShellCommandLineGetFlag (ParamPackage, L"-i"); CumulativeMode = ShellCommandLineGetFlag (ParamPackage, L"-c"); // Options with Values CmdLineArg = ShellCommandLineGetValue (ParamPackage, L"-n"); if (CmdLineArg == NULL) { Number2Display = DEFAULT_DISPLAYCOUNT; } else { Number2Display = StrDecimalToUintn(CmdLineArg); if (Number2Display == 0) { Number2Display = MAXIMUM_DISPLAYCOUNT; } } CmdLineArg = ShellCommandLineGetValue (ParamPackage, L"-t"); if (CmdLineArg == NULL) { mInterestThreshold = DEFAULT_THRESHOLD; // 1ms := 1,000 us } else { mInterestThreshold = StrDecimalToUint64(CmdLineArg); } // Handle Flag combinations and default behaviors // If both TraceMode and ProfileMode are FALSE, set them both to TRUE if ((! TraceMode) && (! ProfileMode)) { TraceMode = TRUE; #if PROFILING_IMPLEMENTED ProfileMode = TRUE; #endif // PROFILING_IMPLEMENTED } // // Initialize the pre-defined cumulative data. // InitCumulativeData (); // // Init the custom cumulative data. // CustomCumulativeToken = ShellCommandLineGetValue (ParamPackage, L"-c"); if (CustomCumulativeToken != NULL) { CustomCumulativeData = AllocateZeroPool (sizeof (PERF_CUM_DATA)); if (CustomCumulativeData == NULL) { return SHELL_OUT_OF_RESOURCES; } CustomCumulativeData->MinDur = PERF_MAXDUR; CustomCumulativeData->MaxDur = 0; CustomCumulativeData->Count = 0; CustomCumulativeData->Duration = 0; NameSize = StrLen (CustomCumulativeToken) + 1; CustomCumulativeData->Name = AllocateZeroPool (NameSize); if (CustomCumulativeData->Name == NULL) { FreePool (CustomCumulativeData); return SHELL_OUT_OF_RESOURCES; } UnicodeStrToAsciiStrS (CustomCumulativeToken, CustomCumulativeData->Name, NameSize); } // // Timer specific processing // // Get the Performance counter characteristics: // Freq = Frequency in Hz // StartCount = Value loaded into the counter when it starts counting // EndCount = Value counter counts to before it needs to be reset // Status = EfiGetSystemConfigurationTable (&gPerformanceProtocolGuid, (VOID **) &PerformanceProperty); if (EFI_ERROR (Status) || (PerformanceProperty == NULL)) { ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_PERF_PROPERTY_NOT_FOUND), mDpHiiHandle); goto Done; } TimerInfo.Frequency = (UINT32)DivU64x32 (PerformanceProperty->Frequency, 1000); TimerInfo.StartCount = 0; TimerInfo.EndCount = 0xFFFF; TimerInfo.CountUp = TRUE; // // Print header // // print DP's build version ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_DP_BUILD_REVISION), mDpHiiHandle, DP_MAJOR_VERSION, DP_MINOR_VERSION); // print performance timer characteristics ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_DP_KHZ), mDpHiiHandle, TimerInfo.Frequency); if (VerboseMode && !RawMode) { StringPtr = HiiGetString (mDpHiiHandle, (EFI_STRING_ID) (TimerInfo.CountUp ? STRING_TOKEN (STR_DP_UP) : STRING_TOKEN (STR_DP_DOWN)), NULL); ASSERT (StringPtr != NULL); // Print Timer count range and direction ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_DP_TIMER_PROPERTIES), mDpHiiHandle, StringPtr, TimerInfo.StartCount, TimerInfo.EndCount ); ShellPrintHiiEx (-1, -1, NULL, STRING_TOKEN (STR_DP_VERBOSE_THRESHOLD), mDpHiiHandle, mInterestThreshold); } /**************************************************************************** **** Print Sections based on command line options **** **** Option modes have the following priority: **** v Verbose -- Valid in combination with any other options **** t Threshold -- Modifies All, Raw, and Cooked output **** Default is 0 for All and Raw mode **** Default is DEFAULT_THRESHOLD for "Cooked" mode **** n Number2Display Used by All and Raw mode. Otherwise ignored. **** A All -- R and S options are ignored **** R Raw -- S option is ignored **** s Summary -- Modifies "Cooked" output only **** Cooked (Default) **** **** The All, Raw, and Cooked modes are modified by the Trace and Profile **** options. **** !T && !P := (0) Default, Both are displayed **** T && !P := (1) Only Trace records are displayed **** !T && P := (2) Only Profile records are displayed **** T && P := (3) Same as Default, both are displayed ****************************************************************************/ GatherStatistics (CustomCumulativeData); if (CumulativeMode) { ProcessCumulative (CustomCumulativeData); } else if (AllMode) { if (TraceMode) { Status = DumpAllTrace( Number2Display, ExcludeMode); if (Status == EFI_ABORTED) { ShellStatus = SHELL_ABORTED; goto Done; } } if (ProfileMode) { DumpAllProfile( Number2Display, ExcludeMode); } } else if (RawMode) { if (TraceMode) { Status = DumpRawTrace( Number2Display, ExcludeMode); if (Status == EFI_ABORTED) { ShellStatus = SHELL_ABORTED; goto Done; } } if (ProfileMode) { DumpRawProfile( Number2Display, ExcludeMode); } } else { //------------- Begin Cooked Mode Processing if (TraceMode) { ProcessPhases (); if ( ! SummaryMode) { Status = ProcessHandles ( ExcludeMode); if (Status == EFI_ABORTED) { ShellStatus = SHELL_ABORTED; goto Done; } Status = ProcessPeims (); if (Status == EFI_ABORTED) { ShellStatus = SHELL_ABORTED; goto Done; } Status = ProcessGlobal (); if (Status == EFI_ABORTED) { ShellStatus = SHELL_ABORTED; goto Done; } ProcessCumulative (NULL); } } if (ProfileMode) { DumpAllProfile( Number2Display, ExcludeMode); } } //------------- End of Cooked Mode Processing if ( VerboseMode || SummaryMode) { DumpStatistics(); } Done: if (ParamPackage != NULL) { ShellCommandLineFreeVarList (ParamPackage); } SHELL_FREE_NON_NULL (StringPtr); if (CustomCumulativeData != NULL) { SHELL_FREE_NON_NULL (CustomCumulativeData->Name); } SHELL_FREE_NON_NULL (CustomCumulativeData); SHELL_FREE_NON_NULL (mMeasurementList); SHELL_FREE_NON_NULL (mCacheHandleGuidTable); mMeasurementNum = 0; mCachePairCount = 0; return ShellStatus; } /** Retrive HII package list from ImageHandle and publish to HII database. @param ImageHandle The image handle of the process. @return HII handle. **/ EFI_HANDLE InitializeHiiPackage ( EFI_HANDLE ImageHandle ) { EFI_STATUS Status; EFI_HII_PACKAGE_LIST_HEADER *PackageList; EFI_HANDLE HiiHandle; // // Retrieve HII package list from ImageHandle // Status = gBS->OpenProtocol ( ImageHandle, &gEfiHiiPackageListProtocolGuid, (VOID **)&PackageList, ImageHandle, NULL, EFI_OPEN_PROTOCOL_GET_PROTOCOL ); ASSERT_EFI_ERROR (Status); if (EFI_ERROR (Status)) { return NULL; } // // Publish HII package list to HII Database. // Status = gHiiDatabase->NewPackageList ( gHiiDatabase, PackageList, NULL, &HiiHandle ); ASSERT_EFI_ERROR (Status); if (EFI_ERROR (Status)) { return NULL; } return HiiHandle; }
33.04276
162
0.612717
107e50213f1a65828bc39118c0ccefb1b3b7aef5
15,943
h
C
PololuBuzzer.h
jeppefrandsen/zumo-32u4-arduino-library
9756156895cca55344c0dcbfbcefa99b59c03573
[ "MIT" ]
59
2015-09-18T20:56:49.000Z
2021-12-10T07:26:43.000Z
PololuBuzzer.h
jeppefrandsen/zumo-32u4-arduino-library
9756156895cca55344c0dcbfbcefa99b59c03573
[ "MIT" ]
6
2015-12-09T02:34:52.000Z
2021-12-20T14:51:08.000Z
PololuBuzzer.h
jeppefrandsen/zumo-32u4-arduino-library
9756156895cca55344c0dcbfbcefa99b59c03573
[ "MIT" ]
70
2015-09-18T20:56:34.000Z
2022-03-16T08:58:47.000Z
// Copyright Pololu Corporation. For more information, see http://www.pololu.com/ /*! \file PololuBuzzer.h * * See the PololuBuzzer class reference for more information about this library. * * The main repository for this library is * https://github.com/pololu/pololu-buzzer-arduino, though copies of this * library also exist in other repositories. * * \class PololuBuzzer PololuBuzzer.h * \brief Play beeps and music with the buzzer. * * The PololuBuzzer library allows various sounds to be played through a buzzer, * from simple beeps to complex tunes. * * On the ATmega328P/168 boards, this library uses Timer 2 and pin 3 (PD3/OC2B). * On ATmega32U4 boards, this library uses Timer 4 and pin 6 (PD7/OC4D). This * library will conflict will other libraries that use the same timer or pin. * * Note durations are timed using a timer overflow interrupt * (`TIMER2_OVF`/`TIMER4_OVF`), which will briefly interrupt execution of your * main program at the frequency of the sound being played. In most cases, the * interrupt-handling routine is very short (several microseconds). However, * when playing a sequence of notes in `PLAY_AUTOMATIC` mode (the default mode) * with the `play()` command, this interrupt takes much longer than normal * (perhaps several hundred microseconds) every time it starts a new note. It is * important to take this into account when writing timing-critical code. * * This library is fully compatible with the OrangutanBuzzer functions * in the [Pololu AVR C/C++ Library](http://www.pololu.com/docs/0J18) * and the [ZumoBuzzer library](https://github.com/pololu/zumo-shield), * so any sequences and melodies written for those libraries will also work * with the equivalent PololuBuzzer functions. */ #pragma once #include <avr/pgmspace.h> /*! \brief Specifies that the sequence of notes will play with no further action * required by the user. */ #define PLAY_AUTOMATIC 0 /*! \brief Specified that the user will need to call `playCheck()` regularly. */ #define PLAY_CHECK 1 // n // Equal Tempered Scale is given by f = f * a // n o // // where f is chosen as A above middle C (A4) at f = 440 Hz // o o // and a is given by the twelfth root of 2 (~1.059463094359) /*! \anchor note_macros * * \name Note Macros * \a x specifies the octave of the note * @{ */ #define NOTE_C(x) ( 0 + (x)*12) #define NOTE_C_SHARP(x) ( 1 + (x)*12) #define NOTE_D_FLAT(x) ( 1 + (x)*12) #define NOTE_D(x) ( 2 + (x)*12) #define NOTE_D_SHARP(x) ( 3 + (x)*12) #define NOTE_E_FLAT(x) ( 3 + (x)*12) #define NOTE_E(x) ( 4 + (x)*12) #define NOTE_F(x) ( 5 + (x)*12) #define NOTE_F_SHARP(x) ( 6 + (x)*12) #define NOTE_G_FLAT(x) ( 6 + (x)*12) #define NOTE_G(x) ( 7 + (x)*12) #define NOTE_G_SHARP(x) ( 8 + (x)*12) #define NOTE_A_FLAT(x) ( 8 + (x)*12) #define NOTE_A(x) ( 9 + (x)*12) #define NOTE_A_SHARP(x) (10 + (x)*12) #define NOTE_B_FLAT(x) (10 + (x)*12) #define NOTE_B(x) (11 + (x)*12) /*! \brief silences buzzer for the note duration */ #define SILENT_NOTE 0xFF /*! \brief frequency bit that indicates Hz/10<br> * e.g. \a frequency = `(445 | DIV_BY_10)` gives a frequency of 44.5 Hz */ #define DIV_BY_10 (1 << 15) /*! @} */ class PololuBuzzer { public: /*! \brief Plays the specified frequency for the specified duration. * * \param freq Frequency to play in Hz (or 0.1 Hz if the `DIV_BY_10` bit * is set). * \param duration Duration of the note in milliseconds. * \param volume Volume of the note (0--15). * * The \a frequency argument must be between 40 Hz and 10 kHz. If the most * significant bit of \a frequency is set, the frequency played is the value * of the lower 15 bits of \a frequency in units of 0.1 Hz. Therefore, you can * play a frequency of 44.5 Hz by using a \a frequency of `(DIV_BY_10 | 445)`. * If the most significant bit of \a frequency is not set, the units for * frequency are Hz. The \a volume argument controls the buzzer volume, with * 15 being the loudest and 0 being the quietest. A \a volume of 15 supplies * the buzzer with a 50% duty cycle PWM at the specified \a frequency. * Lowering \a volume by one halves the duty cycle (so 14 gives a 25% duty * cycle, 13 gives a 12.5% duty cycle, etc). The volume control is somewhat * crude (especially on the ATmega328/168) and should be thought of as a bonus * feature. * * This function plays the note in the background while your program continues * to execute. If you call another buzzer function while the note is playing, * the new function call will overwrite the previous and take control of the * buzzer. If you want to string notes together, you should either use the * `play()` function or put an appropriate delay after you start a note * playing. You can use the `is_playing()` function to figure out when the * buzzer is through playing its note or melody. * * ### Example ### * * ~~~{.cpp} * PololuBuzzer buzzer; * * ... * * // play a 6 kHz note for 250 ms at a lower volume * buzzer.playFrequency(6000, 250, 12); * * // wait for buzzer to finish playing the note * while (buzzer.isPlaying()); * * // play a 44.5 Hz note for 1 s at full volume * buzzer.playFrequency(DIV_BY_10 | 445, 1000, 15); * ~~~ * * \warning \a frequency &times; \a duration / 1000 must be no greater than * 0xFFFF (65535). This means you can't use a duration of 65535 ms for * frequencies greater than 1 kHz. For example, the maximum duration you can * use for a frequency of 10 kHz is 6553 ms. If you use a duration longer than * this, you will produce an integer overflow that can result in unexpected * behavior. */ static void playFrequency(unsigned int freq, unsigned int duration, unsigned char volume); /*! \brief Plays the specified note for the specified duration. * * \param note Note to play (see \ref note_macros "Note Macros"). * \param duration Duration of the note in milliseconds. * \param volume Volume of the note (0--15). * * The \a note argument is an enumeration for the notes of the equal tempered * scale (ETS). See \ref note_macros "Note Macros" for more information. The * \a volume argument controls the buzzer volume, with 15 being the loudest * and 0 being the quietest. A \a volume of 15 supplies the buzzer with a 50% * duty cycle PWM at the specified \a frequency. Lowering \a volume by one * halves the duty cycle (so 14 gives a 25% duty cycle, 13 gives a 12.5% duty * cycle, etc). The volume control is somewhat crude (especially on the * ATmega328/168) and should be thought of as a bonus feature. * * This function plays the note in the background while your program continues * to execute. If you call another buzzer function while the note is playing, * the new function call will overwrite the previous and take control of the * buzzer. If you want to string notes together, you should either use the * `play()` function or put an appropriate delay after you start a note * playing. You can use the `is_playing()` function to figure out when the * buzzer is through playing its note or melody. */ static void playNote(unsigned char note, unsigned int duration, unsigned char volume); /*! \brief Plays the specified sequence of notes. * * \param sequence Char array containing a sequence of notes to play. * * If the play mode is `PLAY_AUTOMATIC` (default), the sequence of notes will * play with no further action required by the user. If the play mode is * `PLAY_CHECK`, the user will need to call `playCheck()` in the main loop to * initiate the playing of each new note in the sequence. The play mode can be * changed while the sequence is playing. The sequence syntax is modeled after * the PLAY commands in GW-BASIC, with just a few differences. * * The notes are specified by the characters **C**, **D**, **E**, **F**, * **G**, **A**, and **B**, and they are played by default as "quarter notes" * with a length of 500 ms. This corresponds to a tempo of 120 beats/min. * Other durations can be specified by putting a number immediately after the * note. For example, C8 specifies C played as an eighth note, with half the * duration of a quarter note. The special note **R** plays a rest (no sound). * The sequence parser is case-insensitive and ignores spaces, which may be * used to format your music nicely. * * Various control characters alter the sound: * <table> * <tr><th>Control character(s)</th><th>Effect</th></tr> * <tr><td><strong>A--G</strong></td> * <td>Specifies a note that will be played.</td></tr> * <tr><td><strong>R</strong></td> * <td>Specifies a rest (no sound for the duration of the note).</td></tr> * <tr><td><strong>+</strong></strong> or <strong>#</strong> after a note</td> * <td>Raises the preceding note one half-step.</td></tr> * <tr><td><strong>-</strong> after a note</td> * <td>Lowers the preceding note one half-step.</td></tr> * <tr><td><strong>1--2000</strong> after a note</td> * <td>Determines the duration of the preceding note. For example, C16 * specifies C played as a sixteenth note (1/16th the length of a * whole note).</td></tr> * <tr><td><strong>.</strong> after a note</td> * <td>"Dots" the preceding note, increasing the length by 50%. Each * additional dot adds half as much as the previous dot, so that "A.." * is 1.75 times the length of "A".</td></tr> * <tr><td><strong>></strong> before a note</td> * <td>Plays the following note one octave higher.</td></tr> * <tr><td><strong><</strong> before a note</td> * <td>Plays the following note one octave lower.</td></tr> * <tr><td><strong>O</strong> followed by a number</td> * <td>Sets the octave. (default: **O4**)</td></tr> * <tr><td><strong>T</strong> followed by a number</td> * <td>Sets the tempo in beats per minute (BPM). (default: **T120**)</td></tr> * <tr><td><strong>L</strong> followed by a number</td> * <td>Sets the default note duration to the type specified by the number: * 4 for quarter notes, 8 for eighth notes, 16 for sixteenth notes, * etc. (default: **L4**)</td></tr> * <tr><td><strong>V</strong> followed by a number</td> * <td>Sets the music volume (0--15). (default: **V15**)</td></tr> * <tr><td><strong>MS</strong></td> * <td>Sets all subsequent notes to play play staccato -- each note is * played for 1/2 of its allotted time, followed by an equal period of * silence.</td></tr> * <tr><td><strong>ML</strong></td> * <td>Sets all subsequent notes to play legato -- each note is played for * full length. This is the default setting.</td></tr> * <tr><td><strong>!</strong></td> * <td>Resets the octave, tempo, duration, volume, and staccato setting to * their default values. These settings persist from one `play()` to the * next, which allows you to more conveniently break up your music into * reusable sections.</td></tr> * </table> * * This function plays the string of notes in the background while your * program continues to execute. If you call another buzzer function while the * melody is playing, the new function call will overwrite the previous and * take control of the buzzer. If you want to string melodies together, you * should put an appropriate delay after you start a melody playing. You can * use the `is_playing()` function to figure out when the buzzer is through * playing the melody. * * ### Example ### * * ~~~{.cpp} * PololuBuzzer buzzer; * * ... * * // play a C major scale up and back down: * buzzer.play("!L16 V8 cdefgab>cbagfedc"); * while (buzzer.isPlaying()); * * // the first few measures of Bach's fugue in D-minor * buzzer.play("!T240 L8 agafaea dac+adaea fa<aa<bac#a dac#adaea f4"); * ~~~ */ static void play(const char *sequence); /*! \brief Plays the specified sequence of notes from program space. * * \param sequence Char array in program space containing a sequence of notes * to play. * * A version of `play()` that takes a pointer to program space instead of RAM. * This is desirable since RAM is limited and the string must be in program * space anyway. * * ### Example ### * * ~~~{.cpp} * #include <avr/pgmspace.h> * * PololuBuzzer buzzer; * const char melody[] PROGMEM = "!L16 V8 cdefgab>cbagfedc"; * * ... * * buzzer.playFromProgramSpace(melody); * ~~~ */ static void playFromProgramSpace(const char *sequence); /*! \brief Controls whether `play()` sequence is played automatically or * must be driven with `playCheck()`. * * \param mode Play mode (either `PLAY_AUTOMATIC` or `PLAY_CHECK`). * * This method lets you determine whether the notes of the `play()` sequence * are played automatically in the background or are driven by the * `playCheck()` method. If \a mode is `PLAY_AUTOMATIC`, the sequence will * play automatically in the background, driven by the timer overflow * interrupt. The interrupt will take a considerable amount of time to execute * when it starts the next note in the sequence playing, so it is recommended * that you do not use automatic-play if you cannot tolerate being interrupted * for more than a few microseconds. If \a mode is `PLAY_CHECK`, you can * control when the next note in the sequence is played by calling the * `playCheck()` method at acceptable points in your main loop. If your main * loop has substantial delays, it is recommended that you use automatic-play * mode rather than play-check mode. Note that the play mode can be changed * while the sequence is being played. The mode is set to `PLAY_AUTOMATIC` by * default. */ static void playMode(unsigned char mode); /*! \brief Starts the next note in a sequence, if necessary, in `PLAY_CHECK` * mode. * * \return 0 if sequence is complete, 1 otherwise. * * This method only needs to be called if you are in `PLAY_CHECK` mode. It * checks to see whether it is time to start another note in the sequence * initiated by `play()`, and starts it if so. If it is not yet time to start * the next note, this method returns without doing anything. Call this as * often as possible in your main loop to avoid delays between notes in the * sequence. This method returns 0 (false) if the melody to be played is * complete, otherwise it returns 1 (true). */ static unsigned char playCheck(); /*! \brief Checks whether a note, frequency, or sequence is being played. * * \return 1 if the buzzer is current playing a note, frequency, or sequence; * 0 otherwise. * * This method returns 1 (true) if the buzzer is currently playing a * note/frequency or if it is still playing a sequence started by `play()`. * Otherwise, it returns 0 (false). You can poll this method to determine when * it's time to play the next note in a sequence, or you can use it as the * argument to a delay loop to wait while the buzzer is busy. */ static unsigned char isPlaying(); /*! \brief Stops any note, frequency, or melody being played. * * This method will immediately silence the buzzer and terminate any * note/frequency/melody that is currently playing. */ static void stopPlaying(); private: // initializes timer for buzzer control static void init2(); static void init(); };
45.036723
84
0.665684
319e87e5b9ce0730a46fb5519d30147efc417553
1,574
h
C
include/planning/math/discretized_points_smoothing/cos_theta_ipopt_interface.h
Chufan1990/HLC
83a9bc1e949bb74b015bb60df097cd4d265db052
[ "Apache-2.0" ]
null
null
null
include/planning/math/discretized_points_smoothing/cos_theta_ipopt_interface.h
Chufan1990/HLC
83a9bc1e949bb74b015bb60df097cd4d265db052
[ "Apache-2.0" ]
null
null
null
include/planning/math/discretized_points_smoothing/cos_theta_ipopt_interface.h
Chufan1990/HLC
83a9bc1e949bb74b015bb60df097cd4d265db052
[ "Apache-2.0" ]
2
2021-12-22T12:55:17.000Z
2021-12-27T06:04:07.000Z
/** * @file */ #pragma once #include <cppad/cppad.hpp> #include <utility> #include <vector> namespace autoagric { namespace planning { class CosThetaIpoptInterface { public: typedef CPPAD_TESTVECTOR(double) Dvector; typedef CPPAD_TESTVECTOR(CppAD::AD<double>) ADvector; CosThetaIpoptInterface(const std::vector<std::pair<double, double>>& point, const std::vector<double>& bounds); virtual ~CosThetaIpoptInterface() = default; void set_weight_cos_included_angle(const double weight_cos_included_angle); void set_weight_anchor_points(const double weight_anchor_points); void set_weight_length(const double weight_length); void get_optimization_results(std::vector<double>* ptr_x, std::vector<double>* ptr_y) const; bool get_bounds_info(int n, Dvector& x_l, Dvector& x_u, int m, Dvector& g_l, Dvector& g_u); bool get_starting_point(int n, Dvector& x); void operator()(ADvector& fg, const ADvector& x); private: template <class T> bool eval_obj(const T& x, T& obj_value); template <class T> bool eval_constraints(const T& x, T& g); std::vector<std::pair<double, double>> ref_points_; std::vector<double> bounds_; std::vector<double> opt_x_; std::vector<double> opt_y_; size_t num_of_variables_ = 0; size_t num_of_constraints_ = 0; size_t num_of_points_ = 0; double weight_cos_included_angle_ = 0.0; double weight_anchor_points_ = 0.0; double weight_length_ = 0.0; }; } // namespace planning } // namespace autoagric
22.811594
78
0.699492
2ea56556cfb9e4822fd9e1dcbebf9b119e0c10f5
11,771
c
C
src/uct/tcp/tcp_ep.c
anshumang/ucx
7acbc65032b866887decd2ada0c44c1da09e18db
[ "BSD-3-Clause" ]
null
null
null
src/uct/tcp/tcp_ep.c
anshumang/ucx
7acbc65032b866887decd2ada0c44c1da09e18db
[ "BSD-3-Clause" ]
null
null
null
src/uct/tcp/tcp_ep.c
anshumang/ucx
7acbc65032b866887decd2ada0c44c1da09e18db
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (C) Mellanox Technologies Ltd. 2001-2019. ALL RIGHTS RESERVED. * See file LICENSE for terms. */ #include "tcp.h" #include <ucs/async/async.h> #define UCT_TCP_AM_SHORT_PACK_DATA(_pack_f, _target_buf, _target_length, \ _am_payload, _payload_length, _am_header) \ do { \ *((uint64_t*)(_target_buf)) = (_am_header); \ _pack_f((uint8_t*)(_target_buf) + sizeof(_am_header), \ _am_payload, _payload_length); \ _target_length = sizeof(_am_header) + _payload_length; \ } while (0) #define UCT_TCP_AM_BCOPY_PACK_DATA(_pack_f, _target_buf, _target_length, \ _am_arg, ...) \ _target_length = _pack_f(_target_buf, _am_arg) #define UCT_TCP_AM_PREPARE(_ep, _id, _len_thr, _hdr, \ _pack_f, _am_payload, _payload_length, \ _am_header, _method, _name) \ do { \ UCT_CHECK_AM_ID(_id); \ \ if (!uct_tcp_ep_can_send(_ep)) { \ return UCS_ERR_NO_RESOURCE; \ } \ \ (_hdr) = (_ep)->buf; \ (_hdr)->am_id = _id; \ \ UCT_TCP_AM_ ## _method ## _PACK_DATA(_pack_f, (_hdr) + 1, (_hdr)->length, \ _am_payload, _payload_length, \ _am_header); \ \ UCT_CHECK_LENGTH((_hdr)->length, 0, _len_thr, _name); \ UCT_TL_EP_STAT_OP(&(_ep)->super, AM, _method, (_hdr)->length); \ } while (0) static void uct_tcp_ep_epoll_ctl(uct_tcp_ep_t *ep, int op) { uct_tcp_iface_t *iface = ucs_derived_of(ep->super.super.iface, uct_tcp_iface_t); struct epoll_event epoll_event; int ret; memset(&epoll_event, 0, sizeof(epoll_event)); epoll_event.data.ptr = ep; epoll_event.events = ep->events; ret = epoll_ctl(iface->epfd, op, ep->fd, &epoll_event); if (ret < 0) { ucs_fatal("epoll_ctl(epfd=%d, op=%d, fd=%d) failed: %m", iface->epfd, op, ep->fd); } } static inline int uct_tcp_ep_can_send(uct_tcp_ep_t *ep) { ucs_assert(ep->offset <= ep->length); /* TODO optimize to allow partial sends/message coalescing */ return ep->length == 0; } static UCS_CLASS_INIT_FUNC(uct_tcp_ep_t, uct_tcp_iface_t *iface, int fd, const struct sockaddr_in *dest_addr) { ucs_status_t status; UCS_CLASS_CALL_SUPER_INIT(uct_base_ep_t, &iface->super) self->buf = ucs_malloc(ucs_max(iface->config.buf_size, iface->config.short_size), "tcp_buf"); if (self->buf == NULL) { return UCS_ERR_NO_MEMORY; } self->events = 0; self->offset = 0; self->length = 0; ucs_queue_head_init(&self->pending_q); if (fd == -1) { status = ucs_tcpip_socket_create(&self->fd); if (status != UCS_OK) { goto err; } /* TODO use non-blocking connect */ status = uct_tcp_socket_connect(self->fd, dest_addr); if (status != UCS_OK) { goto err_close; } } else { self->fd = fd; } status = ucs_sys_fcntl_modfl(self->fd, O_NONBLOCK, 0); if (status != UCS_OK) { goto err_close; } status = uct_tcp_iface_set_sockopt(iface, self->fd); if (status != UCS_OK) { goto err_close; } UCS_ASYNC_BLOCK(iface->super.worker->async); ucs_list_add_tail(&iface->ep_list, &self->list); UCS_ASYNC_UNBLOCK(iface->super.worker->async); ucs_debug("tcp_ep %p: created on iface %p, fd %d", self, iface, self->fd); return UCS_OK; err_close: close(self->fd); err: return status; } static UCS_CLASS_CLEANUP_FUNC(uct_tcp_ep_t) { uct_tcp_iface_t *iface = ucs_derived_of(self->super.super.iface, uct_tcp_iface_t); ucs_debug("tcp_ep %p: destroying", self); UCS_ASYNC_BLOCK(iface->super.worker->async); ucs_list_del(&self->list); UCS_ASYNC_UNBLOCK(iface->super.worker->async); ucs_free(self->buf); close(self->fd); } UCS_CLASS_DEFINE(uct_tcp_ep_t, uct_base_ep_t); UCS_CLASS_DEFINE_NAMED_NEW_FUNC(uct_tcp_ep_create, uct_tcp_ep_t, uct_tcp_ep_t, uct_tcp_iface_t*, int, const struct sockaddr_in*) UCS_CLASS_DEFINE_NAMED_DELETE_FUNC(uct_tcp_ep_destroy, uct_tcp_ep_t, uct_ep_t) ucs_status_t uct_tcp_ep_create_connected(const uct_ep_params_t *params, uct_ep_h *ep_p) { uct_tcp_iface_t *iface = ucs_derived_of(params->iface, uct_tcp_iface_t); uct_tcp_ep_t *tcp_ep = NULL; struct sockaddr_in dest_addr; ucs_status_t status; UCT_EP_PARAMS_CHECK_DEV_IFACE_ADDRS(params); memset(&dest_addr, 0, sizeof(dest_addr)); dest_addr.sin_family = AF_INET; dest_addr.sin_port = *(in_port_t*)params->iface_addr; dest_addr.sin_addr = *(struct in_addr*)params->dev_addr; /* TODO try to reuse existing connection */ status = uct_tcp_ep_create(iface, -1, &dest_addr, &tcp_ep); if (status == UCS_OK) { ucs_debug("tcp_ep %p: connected to %s:%d", tcp_ep, inet_ntoa(dest_addr.sin_addr), ntohs(dest_addr.sin_port)); *ep_p = &tcp_ep->super.super; } return status; } void uct_tcp_ep_mod_events(uct_tcp_ep_t *ep, uint32_t add, uint32_t remove) { int old_events = ep->events; int new_events = (ep->events | add) & ~remove; if (new_events != ep->events) { ep->events = new_events; ucs_trace("tcp_ep %p: set events to %c%c", ep, (new_events & EPOLLIN) ? 'i' : '-', (new_events & EPOLLOUT) ? 'o' : '-'); if (new_events == 0) { uct_tcp_ep_epoll_ctl(ep, EPOLL_CTL_DEL); } else if (old_events != 0) { uct_tcp_ep_epoll_ctl(ep, EPOLL_CTL_MOD); } else { uct_tcp_ep_epoll_ctl(ep, EPOLL_CTL_ADD); } } } static unsigned uct_tcp_ep_send(uct_tcp_ep_t *ep) { uct_tcp_iface_t *iface = ucs_derived_of(ep->super.super.iface, uct_tcp_iface_t); size_t send_length; ucs_status_t status; send_length = ep->length - ep->offset; ucs_assert(send_length > 0); status = uct_tcp_send(ep->fd, ep->buf + ep->offset, &send_length); if (status < 0) { return 0; } ucs_trace_data("tcp_ep %p: sent %zu bytes", ep, send_length); iface->outstanding -= send_length; ep->offset += send_length; if (ep->offset == ep->length) { ep->offset = 0; ep->length = 0; } return send_length > 0; } unsigned uct_tcp_ep_progress_tx(uct_tcp_ep_t *ep) { unsigned count = 0; uct_pending_req_priv_queue_t *priv; ucs_trace_func("ep=%p", ep); if (ep->length > 0) { count += uct_tcp_ep_send(ep); } uct_pending_queue_dispatch(priv, &ep->pending_q, uct_tcp_ep_can_send(ep)); if (uct_tcp_ep_can_send(ep)) { ucs_assert(ucs_queue_is_empty(&ep->pending_q)); uct_tcp_ep_mod_events(ep, 0, EPOLLOUT); } return count; } unsigned uct_tcp_ep_progress_rx(uct_tcp_ep_t *ep) { uct_tcp_iface_t *iface = ucs_derived_of(ep->super.super.iface, uct_tcp_iface_t); uct_tcp_am_hdr_t *hdr; ucs_status_t status; size_t recv_length; ssize_t remainder; ucs_trace_func("ep=%p", ep); /* Receive next chunk of data */ recv_length = iface->config.buf_size - ep->length; ucs_assertv(recv_length > 0, "ep=%p", ep); status = uct_tcp_recv(ep->fd, ep->buf + ep->length, &recv_length); if (status != UCS_OK) { if (status == UCS_ERR_CANCELED) { ucs_debug("tcp_ep %p: remote disconnected", ep); uct_tcp_ep_mod_events(ep, 0, EPOLLIN); uct_tcp_ep_destroy(&ep->super.super); } return 0; } ep->length += recv_length; ucs_trace_data("tcp_ep %p: recvd %zu bytes", ep, recv_length); /* Parse received active messages */ while ((remainder = ep->length - ep->offset) >= sizeof(*hdr)) { hdr = ep->buf + ep->offset; ucs_assert(hdr->length <= (iface->config.buf_size - sizeof(uct_tcp_am_hdr_t))); if (remainder < sizeof(*hdr) + hdr->length) { break; } /* Full message was received */ ep->offset += sizeof(*hdr) + hdr->length; if (hdr->am_id >= UCT_AM_ID_MAX) { ucs_error("invalid am id: %d", hdr->am_id); continue; } uct_iface_trace_am(&iface->super, UCT_AM_TRACE_TYPE_RECV, hdr->am_id, hdr + 1, hdr->length, "RECV fd %d", ep->fd); uct_iface_invoke_am(&iface->super, hdr->am_id, hdr + 1, hdr->length, 0); } /* Move the remaining data to the beginning of the buffer * TODO avoid extra copy on partial receive */ ucs_assert(remainder >= 0); memmove(ep->buf, ep->buf + ep->offset, remainder); ep->offset = 0; ep->length = remainder; return recv_length > 0; } static inline void uct_tcp_ep_am_send(uct_tcp_iface_t *iface, uct_tcp_ep_t *ep, const uct_tcp_am_hdr_t *hdr) { uct_iface_trace_am(&iface->super, UCT_AM_TRACE_TYPE_SEND, hdr->am_id, hdr + 1, hdr->length, "SEND fd %d", ep->fd); ep->length = sizeof(*hdr) + hdr->length; iface->outstanding += ep->length; uct_tcp_ep_send(ep); if (ep->length > 0) { uct_tcp_ep_mod_events(ep, EPOLLOUT, 0); } } ucs_status_t uct_tcp_ep_am_short(uct_ep_h uct_ep, uint8_t am_id, uint64_t header, const void *payload, unsigned length) { uct_tcp_ep_t *ep = ucs_derived_of(uct_ep, uct_tcp_ep_t); uct_tcp_iface_t *iface = ucs_derived_of(uct_ep->iface, uct_tcp_iface_t); uct_tcp_am_hdr_t *hdr; UCT_TCP_AM_PREPARE(ep, am_id, iface->config.short_size - sizeof(*hdr), hdr, memcpy, payload, length, header, SHORT, "am_short"); uct_tcp_ep_am_send(iface, ep, hdr); return UCS_OK; } ssize_t uct_tcp_ep_am_bcopy(uct_ep_h uct_ep, uint8_t am_id, uct_pack_callback_t pack_cb, void *arg, unsigned flags) { uct_tcp_ep_t *ep = ucs_derived_of(uct_ep, uct_tcp_ep_t); uct_tcp_iface_t *iface = ucs_derived_of(uct_ep->iface, uct_tcp_iface_t); uct_tcp_am_hdr_t *hdr; UCT_TCP_AM_PREPARE(ep, am_id, iface->config.buf_size - sizeof(*hdr), hdr, pack_cb, arg, NULL, NULL, BCOPY, "am_bcopy"); uct_tcp_ep_am_send(iface, ep, hdr); return hdr->length; } ucs_status_t uct_tcp_ep_pending_add(uct_ep_h tl_ep, uct_pending_req_t *req, unsigned flags) { uct_tcp_ep_t *ep = ucs_derived_of(tl_ep, uct_tcp_ep_t); if (uct_tcp_ep_can_send(ep)) { return UCS_ERR_BUSY; } uct_pending_req_queue_push(&ep->pending_q, req); UCT_TL_EP_STAT_PEND(&ep->super); return UCS_OK; } void uct_tcp_ep_pending_purge(uct_ep_h tl_ep, uct_pending_purge_callback_t cb, void *arg) { uct_tcp_ep_t *ep = ucs_derived_of(tl_ep, uct_tcp_ep_t); uct_pending_req_priv_queue_t *priv; uct_pending_queue_purge(priv, &ep->pending_q, 1, cb, arg); } ucs_status_t uct_tcp_ep_flush(uct_ep_h tl_ep, unsigned flags, uct_completion_t *comp) { uct_tcp_ep_t *ep = ucs_derived_of(tl_ep, uct_tcp_ep_t); if (!uct_tcp_ep_can_send(ep)) { return UCS_ERR_NO_RESOURCE; } UCT_TL_EP_STAT_FLUSH(&ep->super); return UCS_OK; }
30.814136
87
0.600289
2c37b2376f676eed53752e24933eaecc7274897e
463
h
C
PrivateFrameworks/BackBoardServices.framework/BKSInsecureDrawingAction.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
36
2016-04-20T04:19:04.000Z
2018-10-08T04:12:25.000Z
PrivateFrameworks/BackBoardServices.framework/BKSInsecureDrawingAction.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
null
null
null
PrivateFrameworks/BackBoardServices.framework/BKSInsecureDrawingAction.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
10
2016-06-16T02:40:44.000Z
2019-01-15T03:31:45.000Z
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/BackBoardServices.framework/BackBoardServices */ @interface BKSInsecureDrawingAction : BSAction @property (nonatomic, readonly) NSArray *processIds; - (id)initWithInfo:(id)arg1 timeout:(double)arg2 forResponseOnQueue:(id)arg3 withHandler:(id /* block */)arg4; - (id)initWithInsecureProcessIds:(id)arg1; - (id)keyDescriptionForSetting:(unsigned long long)arg1; - (id)processIds; @end
30.866667
110
0.786177
08b6882639fdba55138a9d0fc75712b9f2d1ff98
1,429
c
C
src/sphere.c
thomasarbona/raytracer
d477a8cd38659d7d95830c0911c79c30b3f7f354
[ "MIT" ]
1
2019-01-10T17:51:36.000Z
2019-01-10T17:51:36.000Z
src/sphere.c
thomasarbona/raytracer
d477a8cd38659d7d95830c0911c79c30b3f7f354
[ "MIT" ]
null
null
null
src/sphere.c
thomasarbona/raytracer
d477a8cd38659d7d95830c0911c79c30b3f7f354
[ "MIT" ]
null
null
null
/* ** intersect_sphere.c for raytracer in /home/arbona/tek1/MUL/raytracer1 ** ** Made by Thomas ARBONA ** Login <thomas.arbona@epitech.eu> ** ** Started on Fri Feb 24 10:12:33 2017 Thomas ARBONA ** Last update Fri Mar 17 14:49:16 2017 Thomas ARBONA */ #include <SFML/System/Vector2.h> #include <SFML/System/Vector3.h> #include <math.h> #include "my.h" sfVector3f normalize_vect(sfVector3f); float intersect_sphere(sfVector3f eye_pos, sfVector3f dir_vector, float radius) { sfVector3f eq; sfVector2f sol; float delta; eq.x = dir_vector.x * dir_vector.x + dir_vector.y * dir_vector.y + dir_vector.z * dir_vector.z; eq.y = 2 * (eye_pos.x * dir_vector.x + eye_pos.y * dir_vector.y + eye_pos.z * dir_vector.z); eq.z = eye_pos.x * eye_pos.x + eye_pos.y * eye_pos.y + eye_pos.z * eye_pos.z - radius * radius; delta = eq.y * eq.y - 4 * eq.x * eq.z; if (delta < 0) return (-1.); if (delta == 0) return (-eq.y / (2 * eq.x)); sol.x = (-eq.y + sqrt(delta)) / (2 * eq.x); sol.y = (delta > 0) ? (-eq.y - sqrt(delta)) / (2 * eq.x) : -1.; if (sol.x < 0 && sol.y < 0) return (-1.); return (sol.x > sol.y ? sol.y < 0 ? sol.x : sol.y : sol.x < 0 ? sol.y : sol.x); } sfVector3f get_normal_sphere(sfVector3f inter) { sfVector3f normal; normal.x = inter.x; normal.y = inter.y; normal.z = inter.z; return (normalize_vect(normal)); }
25.981818
71
0.606718
d3fcc6c39f5c10ed15817f318d5c70236637da7e
1,154
h
C
CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/javax/print/event/PrintJobAttributeEvent.h
chewaiwai/huaweicloud-sdk-c-obs
fbcd3dadd910c22af3a91aeb73ca0fee94d759fb
[ "Apache-2.0" ]
22
2019-06-13T01:16:44.000Z
2022-03-29T02:42:39.000Z
CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/javax/print/event/PrintJobAttributeEvent.h
chewaiwai/huaweicloud-sdk-c-obs
fbcd3dadd910c22af3a91aeb73ca0fee94d759fb
[ "Apache-2.0" ]
26
2019-09-20T06:46:05.000Z
2022-03-11T08:07:14.000Z
CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/javax/print/event/PrintJobAttributeEvent.h
chewaiwai/huaweicloud-sdk-c-obs
fbcd3dadd910c22af3a91aeb73ca0fee94d759fb
[ "Apache-2.0" ]
14
2019-07-15T06:42:39.000Z
2022-02-15T10:32:28.000Z
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*- #ifndef __javax_print_event_PrintJobAttributeEvent__ #define __javax_print_event_PrintJobAttributeEvent__ #pragma interface #include <javax/print/event/PrintEvent.h> extern "Java" { namespace javax { namespace print { class DocPrintJob; namespace attribute { class PrintJobAttributeSet; } namespace event { class PrintJobAttributeEvent; } } } } class javax::print::event::PrintJobAttributeEvent : public ::javax::print::event::PrintEvent { public: PrintJobAttributeEvent(::javax::print::DocPrintJob *, ::javax::print::attribute::PrintJobAttributeSet *); virtual ::javax::print::DocPrintJob * getPrintJob(); virtual ::javax::print::attribute::PrintJobAttributeSet * getAttributes(); private: static const jlong serialVersionUID = -6534469883874742101LL; ::javax::print::attribute::PrintJobAttributeSet * __attribute__((aligned(__alignof__( ::javax::print::event::PrintEvent)))) attributes; public: static ::java::lang::Class class$; }; #endif // __javax_print_event_PrintJobAttributeEvent__
26.227273
137
0.716638
23007d4e22c8f74218038b89e7c37321ff1912dc
13,144
h
C
libvis/src/libvis/lm_optimizer_residual_sum_and_jacobian_accumulator.h
lingbo-yu/camera_calibration
ff5f09fa2253b01b80c24ec600936f5d083d03f3
[ "BSD-3-Clause" ]
474
2019-12-09T06:20:57.000Z
2022-03-31T06:14:38.000Z
libvis/src/libvis/lm_optimizer_residual_sum_and_jacobian_accumulator.h
lingbo-yu/camera_calibration
ff5f09fa2253b01b80c24ec600936f5d083d03f3
[ "BSD-3-Clause" ]
60
2020-01-10T08:41:57.000Z
2022-03-19T15:39:43.000Z
libvis/src/libvis/lm_optimizer_residual_sum_and_jacobian_accumulator.h
lingbo-yu/camera_calibration
ff5f09fa2253b01b80c24ec600936f5d083d03f3
[ "BSD-3-Clause" ]
90
2019-12-09T08:48:06.000Z
2022-03-31T06:14:38.000Z
// Copyright 2019 ETH Zürich, Thomas Schöps // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #pragma once #include "libvis/eigen.h" #include "libvis/libvis.h" #include "libvis/loss_functions.h" namespace vis { template <typename Scalar> class ResidualSumAndJacobianAccumulator { public: ResidualSumAndJacobianAccumulator(int degrees_of_freedom) { jacobian_.resize(degrees_of_freedom); jacobian_.setZero(); } inline void AddInvalidResidual() { // no-op } template <typename LossFunctionT = QuadraticLoss> inline void AddResidual( Scalar residual, const LossFunctionT& loss_function = LossFunctionT()) { cost_ += loss_function.ComputeCost(residual); residual_sum_ += residual; } template <typename LossFunctionT = QuadraticLoss, typename Derived> inline void AddResidual( const MatrixBase<Derived>& residual, const LossFunctionT& loss_function = LossFunctionT()) { Scalar squared_residual = residual.squaredNorm(); cost_ += loss_function.ComputeCostFromSquaredResidual(squared_residual); for (int i = 0; i < Derived::RowsAtCompileTime; ++ i) { residual_sum_ += residual(i); } } template <typename LossFunctionT = QuadraticLoss, typename Derived> inline void AddResidualWithJacobian( Scalar residual, u32 index, const MatrixBase<Derived>& jacobian, const LossFunctionT& loss_function = LossFunctionT()) { cost_ += loss_function.ComputeCost(residual); residual_sum_ += residual; jacobian_.template segment<Derived::ColsAtCompileTime>(index) += jacobian; } template <typename LossFunctionT = QuadraticLoss, typename Derived0, typename Derived1> inline void AddResidualWithJacobian( const MatrixBase<Derived0>& residual, u32 index, const MatrixBase<Derived1>& jacobian, const LossFunctionT& loss_function = LossFunctionT()) { Scalar squared_residual = residual.squaredNorm(); cost_ += loss_function.ComputeCostFromSquaredResidual(squared_residual); for (int i = 0; i < Derived0::RowsAtCompileTime; ++ i) { residual_sum_ += residual(i); jacobian_.template segment<Derived1::ColsAtCompileTime>(index) += jacobian.row(i); } } template <typename LossFunctionT = QuadraticLoss, typename Derived0, typename Derived1> inline void AddResidualWithJacobian( Scalar residual, u32 index0, const MatrixBase<Derived0>& jacobian0, u32 index1, const MatrixBase<Derived1>& jacobian1, bool enable0 = true, bool enable1 = true, const LossFunctionT& loss_function = LossFunctionT()) { cost_ += loss_function.ComputeCost(residual); residual_sum_ += residual; if (enable0) { jacobian_.template segment<Derived0::ColsAtCompileTime>(index0) += jacobian0; } if (enable1) { jacobian_.template segment<Derived1::ColsAtCompileTime>(index1) += jacobian1; } } template <typename LossFunctionT = QuadraticLoss, typename Derived0, typename Derived1, typename Derived2> inline void AddResidualWithJacobian( const MatrixBase<Derived2>& residual, u32 index0, const MatrixBase<Derived0>& jacobian0, u32 index1, const MatrixBase<Derived1>& jacobian1, bool enable0 = true, bool enable1 = true, const LossFunctionT& loss_function = LossFunctionT()) { Scalar squared_residual = residual.squaredNorm(); cost_ += loss_function.ComputeCostFromSquaredResidual(squared_residual); for (int i = 0; i < Derived0::RowsAtCompileTime; ++ i) { residual_sum_ += residual(i); if (enable0) { jacobian_.template segment<Derived0::ColsAtCompileTime>(index0) += jacobian0.row(i); } if (enable1) { jacobian_.template segment<Derived1::ColsAtCompileTime>(index1) += jacobian1.row(i); } } } template <typename LossFunctionT = QuadraticLoss, typename Derived0, typename Derived1, typename Derived2> inline void AddResidualWithJacobian( Scalar residual, u32 index0, const MatrixBase<Derived0>& jacobian0, u32 index1, const MatrixBase<Derived1>& jacobian1, u32 index2, const MatrixBase<Derived2>& jacobian2, bool enable0 = true, bool enable1 = true, bool enable2 = true, const LossFunctionT& loss_function = LossFunctionT()) { cost_ += loss_function.ComputeCost(residual); residual_sum_ += residual; if (enable0) { jacobian_.template segment<Derived0::ColsAtCompileTime>(index0) += jacobian0; } if (enable1) { jacobian_.template segment<Derived1::ColsAtCompileTime>(index1) += jacobian1; } if (enable2) { jacobian_.template segment<Derived2::ColsAtCompileTime>(index2) += jacobian2; } } template <typename LossFunctionT = QuadraticLoss, typename Derived0, typename Derived1, typename Derived2, typename Derived3> inline void AddResidualWithJacobian( const MatrixBase<Derived3>& residual, u32 index0, const MatrixBase<Derived0>& jacobian0, u32 index1, const MatrixBase<Derived1>& jacobian1, u32 index2, const MatrixBase<Derived2>& jacobian2, bool enable0 = true, bool enable1 = true, bool enable2 = true, const LossFunctionT& loss_function = LossFunctionT()) { Scalar squared_residual = residual.squaredNorm(); cost_ += loss_function.ComputeCostFromSquaredResidual(squared_residual); for (int i = 0; i < Derived0::RowsAtCompileTime; ++ i) { residual_sum_ += residual(i); if (enable0) { jacobian_.template segment<Derived0::ColsAtCompileTime>(index0) += jacobian0.row(i); } if (enable1) { jacobian_.template segment<Derived1::ColsAtCompileTime>(index1) += jacobian1.row(i); } if (enable2) { jacobian_.template segment<Derived2::ColsAtCompileTime>(index2) += jacobian2.row(i); } } } template <typename LossFunctionT = QuadraticLoss, typename Derived0, typename Derived1> inline void AddResidualWithJacobian( Scalar residual, const MatrixBase<Derived0>& indices, const MatrixBase<Derived1>& jacobian, const LossFunctionT& loss_function = LossFunctionT()) { cost_ += loss_function.ComputeCost(residual); residual_sum_ += residual; for (int i = 0; i < indices.size(); ++ i) { jacobian_[indices[i]] += jacobian(i); } } template <typename LossFunctionT = QuadraticLoss, typename Derived0, typename Derived1, typename Derived2> inline void AddResidualWithJacobian( const MatrixBase<Derived2>& residual, const MatrixBase<Derived0>& indices, const MatrixBase<Derived1>& jacobian, const LossFunctionT& loss_function = LossFunctionT()) { Scalar squared_residual = residual.squaredNorm(); cost_ += loss_function.ComputeCostFromSquaredResidual(squared_residual); for (int i = 0; i < Derived0::RowsAtCompileTime; ++ i) { residual_sum_ += residual(i); for (int k = 0; k < indices.size(); ++ k) { jacobian_(indices[k]) += jacobian(i, k); } } } template <typename LossFunctionT = QuadraticLoss, typename Derived0, typename Derived1, typename Derived2, typename Derived3> inline void AddResidualWithJacobian( Scalar residual, u32 index0, const MatrixBase<Derived0>& jacobian0, u32 index1, const MatrixBase<Derived1>& jacobian1, const MatrixBase<Derived2>& indices2, const MatrixBase<Derived3>& jacobian2, bool enable0 = true, bool enable1 = true, const LossFunctionT& loss_function = LossFunctionT()) { AddResidualWithJacobian( residual, index0, jacobian0, index1, jacobian1, enable0, enable1, loss_function); for (int i = 0; i < indices2.size(); ++ i) { jacobian_(indices2[i]) += jacobian2(i); } } template <typename LossFunctionT = QuadraticLoss, typename Derived0, typename Derived1, typename Derived2, typename Derived3, typename Derived4> inline void AddResidualWithJacobian( const MatrixBase<Derived4>& residual, u32 index0, const MatrixBase<Derived0>& jacobian0, u32 index1, const MatrixBase<Derived1>& jacobian1, const MatrixBase<Derived2>& indices2, const MatrixBase<Derived3>& jacobian2, bool enable0 = true, bool enable1 = true, const LossFunctionT& loss_function = LossFunctionT()) { AddResidualWithJacobian( residual, index0, jacobian0, index1, jacobian1, enable0, enable1, loss_function); for (int i = 0; i < Derived0::RowsAtCompileTime; ++ i) { for (int k = 0; k < indices2.size(); ++ k) { jacobian_(indices2[k]) += jacobian2(i, k); } } } template <typename LossFunctionT = QuadraticLoss, typename Derived0, typename Derived1, typename Derived2, typename Derived3, typename Derived4> inline void AddResidualWithJacobian( Scalar residual, u32 index0, const MatrixBase<Derived0>& jacobian0, u32 index1, const MatrixBase<Derived1>& jacobian1, u32 index2, const MatrixBase<Derived2>& jacobian2, const MatrixBase<Derived3>& indices3, const MatrixBase<Derived4>& jacobian3, bool enable0 = true, bool enable1 = true, bool enable2 = true, const LossFunctionT& loss_function = LossFunctionT()) { AddResidualWithJacobian( residual, index0, jacobian0, index1, jacobian1, index2, jacobian2, enable0, enable1, enable2, loss_function); for (int i = 0; i < indices3.size(); ++ i) { jacobian_(indices3[i]) += jacobian3(i); } } template <typename LossFunctionT = QuadraticLoss, typename Derived0, typename Derived1, typename Derived2, typename Derived3, typename Derived4, typename Derived5> inline void AddResidualWithJacobian( const MatrixBase<Derived5>& residual, u32 index0, const MatrixBase<Derived0>& jacobian0, u32 index1, const MatrixBase<Derived1>& jacobian1, u32 index2, const MatrixBase<Derived2>& jacobian2, const MatrixBase<Derived3>& indices3, const MatrixBase<Derived4>& jacobian3, bool enable0 = true, bool enable1 = true, bool enable2 = true, const LossFunctionT& loss_function = LossFunctionT()) { AddResidualWithJacobian( residual, index0, jacobian0, index1, jacobian1, index2, jacobian2, enable0, enable1, enable2, loss_function); for (int i = 0; i < Derived0::RowsAtCompileTime; ++ i) { for (int k = 0; k < indices3.size(); ++ k) { jacobian_(indices3[k]) += jacobian3(i, k); } } } inline void FinishedBlockForSchurComplement() const { // no-op } inline Scalar residual_sum() const { return residual_sum_; } inline const Eigen::Matrix<Scalar, 1, Eigen::Dynamic>& jacobian() const { return jacobian_; } inline Scalar cost() const { return cost_; } private: Scalar cost_ = 0; Scalar residual_sum_ = 0; Eigen::Matrix<Scalar, 1, Eigen::Dynamic> jacobian_; }; }
33.616368
95
0.661214
236a52ad94eb705a6be6ea9813838ded256f76e1
7,192
c
C
sources/drivers/phy/phy-exynos4210-usb2.c
fuldaros/paperplane_kernel_wileyfox-spark
bea244880d2de50f4ad14bb6fa5777652232c033
[ "Apache-2.0" ]
2
2018-03-09T23:59:27.000Z
2018-04-01T07:58:39.000Z
sources/drivers/phy/phy-exynos4210-usb2.c
fuldaros/paperplane_kernel_wileyfox-spark
bea244880d2de50f4ad14bb6fa5777652232c033
[ "Apache-2.0" ]
null
null
null
sources/drivers/phy/phy-exynos4210-usb2.c
fuldaros/paperplane_kernel_wileyfox-spark
bea244880d2de50f4ad14bb6fa5777652232c033
[ "Apache-2.0" ]
3
2017-06-24T20:23:09.000Z
2018-03-25T04:30:11.000Z
/* * Samsung SoC USB 1.1/2.0 PHY driver - Exynos 4210 support * * Copyright (C) 2013 Samsung Electronics Co., Ltd. * Author: Kamil Debski <k.debski@samsung.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. */ #include <linux/delay.h> #include <linux/io.h> #include <linux/phy/phy.h> #include <linux/regmap.h> #include "phy-samsung-usb2.h" /* Exynos USB PHY registers */ /* PHY power control */ #define EXYNOS_4210_UPHYPWR 0x0 #define EXYNOS_4210_UPHYPWR_PHY0_SUSPEND BIT(0) #define EXYNOS_4210_UPHYPWR_PHY0_PWR BIT(3) #define EXYNOS_4210_UPHYPWR_PHY0_OTG_PWR BIT(4) #define EXYNOS_4210_UPHYPWR_PHY0_SLEEP BIT(5) #define EXYNOS_4210_UPHYPWR_PHY0 ( \ EXYNOS_4210_UPHYPWR_PHY0_SUSPEND | \ EXYNOS_4210_UPHYPWR_PHY0_PWR | \ EXYNOS_4210_UPHYPWR_PHY0_OTG_PWR | \ EXYNOS_4210_UPHYPWR_PHY0_SLEEP) #define EXYNOS_4210_UPHYPWR_PHY1_SUSPEND BIT(6) #define EXYNOS_4210_UPHYPWR_PHY1_PWR BIT(7) #define EXYNOS_4210_UPHYPWR_PHY1_SLEEP BIT(8) #define EXYNOS_4210_UPHYPWR_PHY1 ( \ EXYNOS_4210_UPHYPWR_PHY1_SUSPEND | \ EXYNOS_4210_UPHYPWR_PHY1_PWR | \ EXYNOS_4210_UPHYPWR_PHY1_SLEEP) #define EXYNOS_4210_UPHYPWR_HSIC0_SUSPEND BIT(9) #define EXYNOS_4210_UPHYPWR_HSIC0_SLEEP BIT(10) #define EXYNOS_4210_UPHYPWR_HSIC0 ( \ EXYNOS_4210_UPHYPWR_HSIC0_SUSPEND | \ EXYNOS_4210_UPHYPWR_HSIC0_SLEEP) #define EXYNOS_4210_UPHYPWR_HSIC1_SUSPEND BIT(11) #define EXYNOS_4210_UPHYPWR_HSIC1_SLEEP BIT(12) #define EXYNOS_4210_UPHYPWR_HSIC1 ( \ EXYNOS_4210_UPHYPWR_HSIC1_SUSPEND | \ EXYNOS_4210_UPHYPWR_HSIC1_SLEEP) /* PHY clock control */ #define EXYNOS_4210_UPHYCLK 0x4 #define EXYNOS_4210_UPHYCLK_PHYFSEL_MASK (0x3 << 0) #define EXYNOS_4210_UPHYCLK_PHYFSEL_OFFSET 0 #define EXYNOS_4210_UPHYCLK_PHYFSEL_48MHZ (0x0 << 0) #define EXYNOS_4210_UPHYCLK_PHYFSEL_24MHZ (0x3 << 0) #define EXYNOS_4210_UPHYCLK_PHYFSEL_12MHZ (0x2 << 0) #define EXYNOS_4210_UPHYCLK_PHY0_ID_PULLUP BIT(2) #define EXYNOS_4210_UPHYCLK_PHY0_COMMON_ON BIT(4) #define EXYNOS_4210_UPHYCLK_PHY1_COMMON_ON BIT(7) /* PHY reset control */ #define EXYNOS_4210_UPHYRST 0x8 #define EXYNOS_4210_URSTCON_PHY0 BIT(0) #define EXYNOS_4210_URSTCON_OTG_HLINK BIT(1) #define EXYNOS_4210_URSTCON_OTG_PHYLINK BIT(2) #define EXYNOS_4210_URSTCON_PHY1_ALL BIT(3) #define EXYNOS_4210_URSTCON_PHY1_P0 BIT(4) #define EXYNOS_4210_URSTCON_PHY1_P1P2 BIT(5) #define EXYNOS_4210_URSTCON_HOST_LINK_ALL BIT(6) #define EXYNOS_4210_URSTCON_HOST_LINK_P0 BIT(7) #define EXYNOS_4210_URSTCON_HOST_LINK_P1 BIT(8) #define EXYNOS_4210_URSTCON_HOST_LINK_P2 BIT(9) /* Isolation, configured in the power management unit */ #define EXYNOS_4210_USB_ISOL_DEVICE_OFFSET 0x704 #define EXYNOS_4210_USB_ISOL_DEVICE BIT(0) #define EXYNOS_4210_USB_ISOL_HOST_OFFSET 0x708 #define EXYNOS_4210_USB_ISOL_HOST BIT(0) /* USBYPHY1 Floating prevention */ #define EXYNOS_4210_UPHY1CON 0x34 #define EXYNOS_4210_UPHY1CON_FLOAT_PREVENTION 0x1 /* Mode switching SUB Device <-> Host */ #define EXYNOS_4210_MODE_SWITCH_OFFSET 0x21c #define EXYNOS_4210_MODE_SWITCH_MASK 1 #define EXYNOS_4210_MODE_SWITCH_DEVICE 0 #define EXYNOS_4210_MODE_SWITCH_HOST 1 enum exynos4210_phy_id { EXYNOS4210_DEVICE, EXYNOS4210_HOST, EXYNOS4210_HSIC0, EXYNOS4210_HSIC1, EXYNOS4210_NUM_PHYS, }; /* * exynos4210_rate_to_clk() converts the supplied clock rate to the value that * can be written to the phy register. */ static int exynos4210_rate_to_clk(unsigned long rate, u32 *reg) { switch (rate) { case 12 * MHZ: *reg = EXYNOS_4210_UPHYCLK_PHYFSEL_12MHZ; break; case 24 * MHZ: *reg = EXYNOS_4210_UPHYCLK_PHYFSEL_24MHZ; break; case 48 * MHZ: *reg = EXYNOS_4210_UPHYCLK_PHYFSEL_48MHZ; break; default: return -EINVAL; } return 0; } static void exynos4210_isol(struct samsung_usb2_phy_instance *inst, bool on) { struct samsung_usb2_phy_driver *drv = inst->drv; u32 offset; u32 mask; switch (inst->cfg->id) { case EXYNOS4210_DEVICE: offset = EXYNOS_4210_USB_ISOL_DEVICE_OFFSET; mask = EXYNOS_4210_USB_ISOL_DEVICE; break; case EXYNOS4210_HOST: offset = EXYNOS_4210_USB_ISOL_HOST_OFFSET; mask = EXYNOS_4210_USB_ISOL_HOST; break; default: return; }; regmap_update_bits(drv->reg_pmu, offset, mask, on ? 0 : mask); } static void exynos4210_phy_pwr(struct samsung_usb2_phy_instance *inst, bool on) { struct samsung_usb2_phy_driver *drv = inst->drv; u32 rstbits = 0; u32 phypwr = 0; u32 rst; u32 pwr; u32 clk; switch (inst->cfg->id) { case EXYNOS4210_DEVICE: phypwr = EXYNOS_4210_UPHYPWR_PHY0; rstbits = EXYNOS_4210_URSTCON_PHY0; break; case EXYNOS4210_HOST: phypwr = EXYNOS_4210_UPHYPWR_PHY1; rstbits = EXYNOS_4210_URSTCON_PHY1_ALL | EXYNOS_4210_URSTCON_PHY1_P0 | EXYNOS_4210_URSTCON_PHY1_P1P2 | EXYNOS_4210_URSTCON_HOST_LINK_ALL | EXYNOS_4210_URSTCON_HOST_LINK_P0; writel(on, drv->reg_phy + EXYNOS_4210_UPHY1CON); break; case EXYNOS4210_HSIC0: phypwr = EXYNOS_4210_UPHYPWR_HSIC0; rstbits = EXYNOS_4210_URSTCON_PHY1_P1P2 | EXYNOS_4210_URSTCON_HOST_LINK_P1; break; case EXYNOS4210_HSIC1: phypwr = EXYNOS_4210_UPHYPWR_HSIC1; rstbits = EXYNOS_4210_URSTCON_PHY1_P1P2 | EXYNOS_4210_URSTCON_HOST_LINK_P2; break; }; if (on) { clk = readl(drv->reg_phy + EXYNOS_4210_UPHYCLK); clk &= ~EXYNOS_4210_UPHYCLK_PHYFSEL_MASK; clk |= drv->ref_reg_val << EXYNOS_4210_UPHYCLK_PHYFSEL_OFFSET; writel(clk, drv->reg_phy + EXYNOS_4210_UPHYCLK); pwr = readl(drv->reg_phy + EXYNOS_4210_UPHYPWR); pwr &= ~phypwr; writel(pwr, drv->reg_phy + EXYNOS_4210_UPHYPWR); rst = readl(drv->reg_phy + EXYNOS_4210_UPHYRST); rst |= rstbits; writel(rst, drv->reg_phy + EXYNOS_4210_UPHYRST); udelay(10); rst &= ~rstbits; writel(rst, drv->reg_phy + EXYNOS_4210_UPHYRST); /* The following delay is necessary for the reset sequence to be * completed */ udelay(80); } else { pwr = readl(drv->reg_phy + EXYNOS_4210_UPHYPWR); pwr |= phypwr; writel(pwr, drv->reg_phy + EXYNOS_4210_UPHYPWR); } } static int exynos4210_power_on(struct samsung_usb2_phy_instance *inst) { /* Order of initialisation is important - first power then isolation */ exynos4210_phy_pwr(inst, 1); exynos4210_isol(inst, 0); return 0; } static int exynos4210_power_off(struct samsung_usb2_phy_instance *inst) { exynos4210_isol(inst, 1); exynos4210_phy_pwr(inst, 0); return 0; } static const struct samsung_usb2_common_phy exynos4210_phys[] = { { .label = "device", .id = EXYNOS4210_DEVICE, .power_on = exynos4210_power_on, .power_off = exynos4210_power_off, }, { .label = "host", .id = EXYNOS4210_HOST, .power_on = exynos4210_power_on, .power_off = exynos4210_power_off, }, { .label = "hsic0", .id = EXYNOS4210_HSIC0, .power_on = exynos4210_power_on, .power_off = exynos4210_power_off, }, { .label = "hsic1", .id = EXYNOS4210_HSIC1, .power_on = exynos4210_power_on, .power_off = exynos4210_power_off, }, {}, }; const struct samsung_usb2_phy_config exynos4210_usb2_phy_config = { .has_mode_switch = 0, .num_phys = EXYNOS4210_NUM_PHYS, .phys = exynos4210_phys, .rate_to_clk = exynos4210_rate_to_clk, };
27.450382
79
0.774889
d6fc67047c1e413e0891a8ae04eee33a4a2184b2
510
h
C
Engine/Core/GameObject.h
Archlisk/FrozenCore
2fad5e0ffbb74644cb63afaa29a93738342ab534
[ "MIT" ]
null
null
null
Engine/Core/GameObject.h
Archlisk/FrozenCore
2fad5e0ffbb74644cb63afaa29a93738342ab534
[ "MIT" ]
null
null
null
Engine/Core/GameObject.h
Archlisk/FrozenCore
2fad5e0ffbb74644cb63afaa29a93738342ab534
[ "MIT" ]
null
null
null
#pragma once #include <Engine.h> #include <Core/Transform.h> class GameObject { public: GameObject(const Vec3 position = Vec3(0), const Vec3 rotation = Vec3(0), const Vec3 scale = Vec3(1)) : transform(position, rotation, scale){} virtual ~GameObject() {} virtual void Render3D() {} virtual void Render2D() {} virtual void Update(double) {} template<typename T> static inline T& Create(const String& name, T* ptr) { return Engine::Get().CreateObject(name, ptr); } Transform transform; };
20.4
102
0.694118
1ea9d9e9b8199f408e655763301184ecb011a73f
6,143
h
C
Practicas/PFinal/letras/include/conjunto_letras.h
josepadial/ED
c095e65843e695e05cbb4d0ae34652d223c45425
[ "MIT" ]
1
2019-12-04T18:11:07.000Z
2019-12-04T18:11:07.000Z
Practicas/PFinal/letras/include/conjunto_letras.h
josepadial/ED
c095e65843e695e05cbb4d0ae34652d223c45425
[ "MIT" ]
null
null
null
Practicas/PFinal/letras/include/conjunto_letras.h
josepadial/ED
c095e65843e695e05cbb4d0ae34652d223c45425
[ "MIT" ]
null
null
null
/* Curso: 2018/2019 Asignatura: Estructura de datos Autores: Jose Antonio Padial Molina Elena Ortiz Moreno Practica: Final "Letras" */ #ifndef __CONJUNTO_LETRAS_H__ #define __CONJUNTO_LETRAS_H__ #include <iostream> #include <set> using namespace std; /** * @brief TDA Letra * @details almacena un caracter, la cantidad de veces que aparece en la bolsa y su puntuacion. */ struct Letra{ char caracter; unsigned int repeticiones; unsigned int puntuacion; /** * @brief Construye una Letra vacia. */ Letra():caracter('\0'),repeticiones(0),puntuacion(0){} /** * @brief Construye una Letra con datos. * @param Char caracter, unsigned int repeticiones y unsigned int puntuacion. */ Letra(char c, unsigned int cnt, unsigned int ptn):caracter(c),repeticiones(cnt),puntuacion(ptn){} /** * @brief Sobrecarga del operador <. */ bool operator<(const Letra &l)const{return caracter < l.caracter;} }; /** * @brief TDA Conjunto Letras * @details se llena desde un fichero */ class Conjunto_letras{ private: set<Letra> datos; public: /** * @brief Construye un diccionario vacio. */ Conjunto_letras(){} /** * @brief Construye un diccionario por copia. * @param Un Conjunto de letras de tipo Conjunto_letras. */ Conjunto_letras(const Conjunto_letras& otro){datos=otro.datos;} /** * @brief Detructor. */ ~Conjunto_letras(){datos.clear();} /** * @brief Obtiene la puntuación de una palabra. * @param Un String donde le pasamos la palabra a consultar. * @return Un entero con la suma de las puntuaciones de las letras de la palabra. */ int puntuacion(string palabra); /** * @brief Limpia el set donde estan los datos. */ void clear(){datos.clear();} /** * @brief Indica si una letra esta en el Conjunto de letras o no. * @param Una letra de tipo Letra. * @return True si la letra esta en el Conjunto de letras y false en caso contrario. */ unsigned int count(const Letra& val)const{return datos.count(val);} /** * @brief Comprueba si esta vacio el set. * @return True si esta vacio false si hay datos. */ bool empty()const{return datos.empty();} /** * @brief Elimina un valor del set. * @param Valor a eliminar. * @return True si lo ha borrado y false si no. */ unsigned int erase(const Letra &val){return datos.erase(val);} /** * @brief Inserta un elemento en el set * @param Valor a insetar * @return Pair con la posicion de inserccion y un bool si lo ha logrado o no. */ pair<set<Letra>::iterator,bool> insert(const Letra &val){return datos.insert(val);} /** * @brief Devuelve el numero de letras en el Conjunto de letras. * @return Tamanio del set datos. */ unsigned int size()const{return datos.size();} /** * @brief Intercambia los valores de dos Conjuntos de letras * @param Otro Conjunto de letras. */ void swap(Conjunto_letras &cl){datos.swap(cl.datos);} /** * @brief Buscar una Letra en una determinada posicion. * @param Posicion a buscar. * @return Valor de la posicon a buscar en el Set. */ Letra at(int n){return this->operator[](n);} /** * @brief Sobrecarga del operador = */ Conjunto_letras& operator=(const Conjunto_letras &cl); /** * @brief Sobrecarga del operador [] */ Letra operator[](int n); /** * @brief Flujo de entrada */ friend istream& operator>>(istream &is, Conjunto_letras &cl); /** * @brief Flujo de salida */ friend ostream& operator<<(ostream &os, const Conjunto_letras &cl); /** * @brief Class iterator * @details Se hace para poder iterar sobre los elementos de tipo Conjunto_letras */ class iterator{ private: set<Letra>::iterator it; public: iterator(){} iterator(const set<Letra>::iterator& otro):it(otro){} iterator(const iterator& otro):it(otro.it){} ~iterator(){} iterator& operator=(const set<Letra>::iterator& otro){it=otro;return *this;} iterator& operator=(const iterator& otro){it=otro.it;return *this;} const Letra& operator*()const{return *it;} iterator& operator++(){++it;return *this;} iterator& operator--(){--it;return *this;} iterator& operator++(int){it++;return *this;} iterator& operator--(int){it--;return *this;} bool operator!=(const iterator& otro){return it != otro.it;} bool operator==(const iterator& otro){return it == otro.it;} }; /** * @brief Class const_iterator * @details Se hace para poder iterar sobre los elementos de tipo Conjunto_letras que sean constantes */ class const_iterator{ private: set<Letra>::const_iterator const_it; public: const_iterator(){} const_iterator(const set<Letra>::const_iterator& otro):const_it(otro){} const_iterator(const const_iterator& otro):const_it(otro.const_it){} ~const_iterator(){} const_iterator& operator=(const set<Letra>::const_iterator& otro){const_it = otro;return *this;} const_iterator& operator=(const const_iterator& otro){const_it = otro.const_it;return *this;} const Letra& operator*()const{return *const_it;} const_iterator& operator++(){++const_it;return *this;} const_iterator& operator--(){--const_it;return *this;} const_iterator& operator++(int){const_it++;return *this;} const_iterator& operator--(int){const_it--;return *this;} bool operator!=(const const_iterator& otro){return const_it != otro.const_it;} bool operator==(const const_iterator& otro){return const_it == otro.const_it;} }; iterator begin(){iterator i = datos.begin();return i;} iterator end(){iterator i = datos.end();return i;} const_iterator begin()const{const_iterator i = datos.begin();return i;} const_iterator end()const{const_iterator i = datos.end();return i;} }; #endif
31.182741
106
0.636822
37f330c2dba38cab139cfeebf5158b40dbe035d5
480
h
C
Main/Source/Signal/Service.h
PeterStegemann/hermesONE
68d04fe78e4723a0edbc7578a92eeffa0ec20c2d
[ "MIT" ]
null
null
null
Main/Source/Signal/Service.h
PeterStegemann/hermesONE
68d04fe78e4723a0edbc7578a92eeffa0ec20c2d
[ "MIT" ]
null
null
null
Main/Source/Signal/Service.h
PeterStegemann/hermesONE
68d04fe78e4723a0edbc7578a92eeffa0ec20c2d
[ "MIT" ]
null
null
null
// Copyright 2014 Peter Stegemann #ifndef SIGNAL_SERVICE_H #define SIGNAL_SERVICE_H #include "PPM.h" #include "AVR/Source/Types.h" #define SIGNAL_SERVICE_PPMS 2 class Signal_Service { private: Signal_PPM ppm0; Signal_PPM ppm1; public: Signal_Service( void); // This is for the interrupt, not for you. void ProcessSignal( uint8_t Index); // Start sending loop. void Start( void); // Get ppm 0 or 1. Signal_PPM* GetPPM( uint8_t Index); }; #endif
15
44
0.70625
23ddf84298d7616e0cae0999541eb8e66ab73cb4
12,312
h
C
ext/scnlib/include/scn/detail/ranges/ranges.h
adarshpatil/gem5
d7d9a18930fc24e3e3e36e3c3a5f3f6a405c80f0
[ "BSD-3-Clause" ]
null
null
null
ext/scnlib/include/scn/detail/ranges/ranges.h
adarshpatil/gem5
d7d9a18930fc24e3e3e36e3c3a5f3f6a405c80f0
[ "BSD-3-Clause" ]
null
null
null
ext/scnlib/include/scn/detail/ranges/ranges.h
adarshpatil/gem5
d7d9a18930fc24e3e3e36e3c3a5f3f6a405c80f0
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2017-2019 Elias Kosunen // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // This file is a part of scnlib: // https://github.com/eliaskosunen/scnlib #ifndef SCN_DETAIL_RANGES_RANGES_H #define SCN_DETAIL_RANGES_RANGES_H #include "../vscan.h" #include "types.h" namespace scn { namespace ranges { SCN_BEGIN_NAMESPACE template <typename Iterator, typename Sentinel> class ranges_result : public scan_result { public: using iterator_type = Iterator; using sentinel_type = Sentinel; using difference_type = ::ranges::difference_type_t<iterator_type>; constexpr ranges_result(iterator_type it, sentinel_type end, scan_result&& base) : scan_result(std::move(base)), m_it(it), m_end(end) { } template <typename Range> constexpr ranges_result(const Range& r, difference_type n, scan_result&& base) : scan_result(std::move(base)), m_it(::ranges::next(::ranges::begin(r), n)), m_end(::ranges::end(r)) { } constexpr iterator_type iterator() const noexcept { return m_it; } constexpr auto view() const noexcept { return ::ranges::make_subrange(iterator(), m_end); } private: iterator_type m_it; sentinel_type m_end; }; template <typename Iterator, typename Range> auto subrange_from(Iterator it, const Range& r) { return ::ranges::make_subrange(it, ::ranges::end(r)); } template <typename CharT> using basic_erased_stream_context = basic_context<erased_range_stream<CharT>>; template <typename CharT> using basic_erased_sized_stream_context = basic_context<erased_sized_range_stream<CharT>>; using erased_stream_context = basic_erased_stream_context<char>; using werased_stream_context = basic_erased_stream_context<wchar_t>; using erased_sized_stream_context = basic_erased_sized_stream_context<char>; using werased_sized_stream_context = basic_erased_sized_stream_context<wchar_t>; template <typename Stream> struct erased_stream_context_type { using char_type = typename Stream::char_type; using type = typename std::conditional< is_sized_stream<Stream>::value, basic_erased_sized_stream_context<char_type>, basic_erased_stream_context<char_type>>::type; }; scan_result vscan(erased_stream_context&); scan_result vscan(werased_stream_context&); scan_result vscan(erased_sized_stream_context&); scan_result vscan(werased_sized_stream_context&); template <typename Range, typename... Args> ranges_result<::ranges::iterator_t<const Range>, ::ranges::sentinel_t<const Range>> scan(const Range& range, basic_string_view< ::ranges::value_type_t<::ranges::iterator_t<Range>>> f, Args&... a) { static_assert(sizeof...(Args) > 0, "Have to scan at least a single argument"); SCN_EXPECT(!f.empty()); auto stream = make_stream(range); using stream_type = decltype(stream); using context_type = basic_context<stream_type>; auto args = make_args<context_type>(a...); auto ctx = context_type(stream, f, args); auto result = vscan(ctx); auto n = static_cast<std::ptrdiff_t>(stream.chars_read()); return {range, n, std::move(result)}; } template <typename Range, typename... Args> ranges_result<::ranges::iterator_t<const Range>, ::ranges::sentinel_t<const Range>> scan(options opt, const Range& range, basic_string_view< ::ranges::value_type_t<::ranges::iterator_t<Range>>> f, Args&... a) { static_assert(sizeof...(Args) > 0, "Have to scan at least a single argument"); SCN_EXPECT(!f.empty()); auto stream = make_stream(range); using stream_type = decltype(stream); using context_type = basic_context<stream_type, basic_locale_ref<::ranges::value_type_t< ::ranges::iterator_t<Range>>>>; auto args = make_args<context_type>(a...); auto ctx = context_type(stream, f, args, opt); auto result = vscan(ctx); return {range, static_cast<std::ptrdiff_t>(stream.chars_read()), std::move(result)}; } template <typename Range, typename... Args> ranges_result<::ranges::iterator_t<const Range>, ::ranges::sentinel_t<const Range>> scan(const Range& range, ::scn::detail::default_t, Args&... a) { static_assert(sizeof...(Args) > 0, "Have to scan at least a single argument"); auto stream = make_stream(range); using stream_type = decltype(stream); using context_type = basic_empty_context<stream_type>; auto args = make_args<context_type>(a...); auto ctx = context_type(stream, sizeof...(Args), args); auto result = vscan(ctx); auto n = static_cast<std::ptrdiff_t>(stream.chars_read()); return {range, n, std::move(result)}; } template <typename Range, typename... Args> ranges_result<::ranges::iterator_t<const Range>, ::ranges::sentinel_t<const Range>> scan(options opt, const Range& range, ::scn::detail::default_t, Args&... a) { static_assert(sizeof...(Args) > 0, "Have to scan at least a single argument"); auto stream = make_stream(range); using stream_type = decltype(stream); using context_type = basic_empty_context<stream_type, basic_locale_ref<::ranges::value_type_t< ::ranges::iterator_t<Range>>>>; auto args = make_args<context_type>(a...); auto ctx = context_type(stream, sizeof...(Args), args, opt); auto result = vscan(ctx); return {range, static_cast<std::ptrdiff_t>(stream.chars_read()), std::move(result)}; } template <typename Range, typename... Args> ranges_result<::ranges::iterator_t<const Range>, ::ranges::sentinel_t<const Range>> scanf(const Range& range, basic_string_view< ::ranges::value_type_t<::ranges::iterator_t<Range>>> f, Args&... a) { static_assert(sizeof...(Args) > 0, "Have to scan at least a single argument"); auto stream = make_stream(range); using stream_type = decltype(stream); using context_type = basic_scanf_context<stream_type>; auto args = make_args<context_type>(a...); auto ctx = context_type(stream, f, args); auto result = vscan(ctx); return {range, static_cast<std::ptrdiff_t>(stream.chars_read()), std::move(result)}; } template <typename Range, typename... Args> ranges_result<::ranges::iterator_t<const Range>, ::ranges::sentinel_t<const Range>> scanf(options opt, const Range& range, basic_string_view< ::ranges::value_type_t<::ranges::iterator_t<Range>>> f, Args&... a) { static_assert(sizeof...(Args) > 0, "Have to scan at least a single argument"); auto stream = make_stream(range); using stream_type = decltype(stream); using context_type = basic_scanf_context<stream_type, basic_locale_ref<::ranges::value_type_t< ::ranges::iterator_t<Range>>>>; auto args = make_args<context_type>(a...); auto ctx = context_type(stream, f, args, opt); auto result = vscan(ctx); return {range, static_cast<std::ptrdiff_t>(stream.chars_read()), std::move(result)}; } template <typename T, typename Iterator, typename Sentinel> class get_value_result : public expected<T> { public: using iterator_type = Iterator; using sentinel_type = Sentinel; using difference_type = ::ranges::difference_type_t<iterator_type>; constexpr get_value_result(iterator_type it, sentinel_type end, expected<T>&& base) : expected<T>(std::move(base)), m_it(it), m_end(end) { } template <typename Range> constexpr get_value_result(const Range& r, difference_type n, expected<T>&& base) : expected<T>(std::move(base)), m_it(::ranges::next(::ranges::begin(r), n)), m_end(::ranges::end(r)) { } constexpr iterator_type iterator() const noexcept { return m_it; } constexpr auto view() const noexcept { return ::ranges::make_subrange(iterator(), m_end); } private: iterator_type m_it; sentinel_type m_end; }; template <typename T, typename Range> get_value_result<T, ::ranges::iterator_t<const Range>, ::ranges::sentinel_t<const Range>> get_value(const Range& r) { auto stream = make_stream(r); using context_type = basic_empty_context<decltype(stream)>; using char_type = typename context_type::char_type; auto args = make_args<context_type>(); auto ctx = context_type(stream, 1, args); auto ret = skip_stream_whitespace(ctx); if (!ret) { return {r, static_cast<std::ptrdiff_t>(stream.chars_read()), expected<T>(ret)}; } T val{}; scanner<char_type, T> sc; ret = sc.scan(val, ctx); if (!ret) { return {r, static_cast<std::ptrdiff_t>(stream.chars_read()), expected<T>(ret)}; } return {r, static_cast<std::ptrdiff_t>(stream.chars_read()), expected<T>(val)}; } template <typename T, typename CharT> auto from_string(basic_string_view<CharT> str) { return get_value<T>(str); } SCN_END_NAMESPACE } // namespace ranges } // namespace scn #if defined(SCN_HEADER_ONLY) && SCN_HEADER_ONLY && \ !defined(SCN_RANGES_VSCAN_CPP) #include "ranges/vscan.cpp" #endif #endif // SCN_DETAIL_RANGES_RANGES_H
37.084337
79
0.541423
f05d28d441d69271d4597a31a04b5e929722b5cb
6,688
h
C
contrib/depends/SDKs/MacOSX10.11.sdk/System/Library/Frameworks/IOKit.framework/Versions/A/Headers/network/IONetworkInterface.h
Amity-Network/amity
3e57379f01af4ca851079c8e469fbda7c8165b47
[ "MIT" ]
28
2019-06-20T13:05:19.000Z
2022-03-28T03:56:22.000Z
contrib/depends/SDKs/MacOSX10.11.sdk/System/Library/Frameworks/IOKit.framework/Versions/A/Headers/network/IONetworkInterface.h
Amity-Network/amity
3e57379f01af4ca851079c8e469fbda7c8165b47
[ "MIT" ]
1
2019-11-17T18:51:10.000Z
2019-11-28T12:53:24.000Z
contrib/depends/SDKs/MacOSX10.11.sdk/System/Library/Frameworks/IOKit.framework/Versions/A/Headers/network/IONetworkInterface.h
Amity-Network/amity
3e57379f01af4ca851079c8e469fbda7c8165b47
[ "MIT" ]
7
2019-06-06T13:05:22.000Z
2020-12-07T12:33:08.000Z
/* * Copyright (c) 1998-2008 Apple Inc. All rights reserved. * * @APPLE_LICENSE_HEADER_START@ * * The contents of this file constitute Original Code as defined in and * are subject to the Apple Public Source License Version 1.1 (the * "License"). You may not use this file except in compliance with the * License. Please obtain a copy of the License at * http://www.apple.com/publicsource and read it before using this file. * * This Original Code and all software distributed under the License are * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the * License for the specific language governing rights and limitations * under the License. * * @APPLE_LICENSE_HEADER_END@ */ #ifndef _IONETWORKINTERFACE_H #define _IONETWORKINTERFACE_H /*! @defined kIONetworkInterfaceClass @abstract The name of the IONetworkInterface class. */ #define kIONetworkInterfaceClass "IONetworkInterface" /*! @defined kIONetworkData @abstract A property of IONetworkInterface objects. @discussion The kIONetworkData property has an OSDictionary value and is a container for the set of IONetworkData objects managed by the interface. Each entry in the dictionary is a key/value pair consisting of the network data name, and an OSDictionary describing the contents of the network data. */ #define kIONetworkData "IONetworkData" /*! @defined kIOInterfaceType @abstract A property of IONetworkInterface objects. @discussion The kIOInterfaceType property has an OSNumber value that specifies the type of network interface that this interface represents. The type constants are defined in bsd/net/if_types.h. */ #define kIOInterfaceType "IOInterfaceType" /*! @defined kIOMaxTransferUnit @abstract A property of IONetworkInterface objects. @discussion The kIOMaxTransferUnit property has an OSNumber value that specifies the maximum transfer unit for the interface in bytes. */ #define kIOMaxTransferUnit "IOMaxTransferUnit" /*! @defined kIOMediaAddressLength @abstract A property of IONetworkInterface objects. @discussion The kIOMediaAddressLength property has an OSNumber value that specifies the size of the media address in bytes. */ #define kIOMediaAddressLength "IOMediaAddressLength" /*! @defined kIOMediaHeaderLength @abstract A property of IONetworkInterface objects. @discussion The kIOMediaHeaderLength property has an OSNumber value that specifies the size of the media header in bytes. */ #define kIOMediaHeaderLength "IOMediaHeaderLength" /*! @defined kIOInterfaceFlags @abstract A property of IONetworkInterface objects. @discussion The kIOInterfaceFlags property has an OSNumber value that specifies the current value of the interface flags. The flag constants are defined in bsd/net/if.h. */ #define kIOInterfaceFlags "IOInterfaceFlags" /*! @defined kIOInterfaceExtraFlags @abstract A property of IONetworkInterface objects. @discussion The kIOInterfaceExtraFlags property has an OSNumber value that specifies the current value of the interface eflags. The eflag constants are defined in bsd/net/if.h. */ #define kIOInterfaceExtraFlags "IOInterfaceExtraFlags" /*! @defined kIOInterfaceUnit @abstract A property of IONetworkInterface objects. @discussion The kIOInterfaceUnit property has an OSNumber value that describes the unit number assigned to the interface object. */ #define kIOInterfaceUnit "IOInterfaceUnit" /*! @defined kIOInterfaceState @abstract A property of IONetworkInterface objects. @discussion The kIOInterfaceState property has an OSNumber value that describes the current state of the interface object. This property is not exported to BSD via the ifnet structure. */ #define kIOInterfaceState "IOInterfaceState" /*! @defined kIOInterfaceNamePrefix @abstract A property of IONetworkInterface objects. @discussion The kIOInterfaceNamePrefix property has an OSString value that describes the string prefix for the BSD name assigned to the interface. */ #define kIOInterfaceNamePrefix "IOInterfaceNamePrefix" /*! @defined kIOPrimaryInterface @abstract A property of IONetworkInterface objects. @discussion The kIOInterfaceNamePrefix property has an OSBoolean value that describes whether the interface is the primary or the built-in network interface. */ #define kIOPrimaryInterface "IOPrimaryInterface" /*! @defined kIOBuiltin @abstract kIOBuiltin is a property of IONetworkInterface objects. It has an OSBoolean value. @discussion The kIOBuiltin property describes whether the interface is built-in. */ #define kIOBuiltin "IOBuiltin" /*! @defined kIOLocation @abstract kIOLocation is a property of IONetworkInterface objects. It has an OSString value. @discussion The kIOLocation property describes the physical location of built-in interfaces. */ #define kIOLocation "IOLocation" /*! @defined kIONetworkNoBSDAttachKey @abstract kIONetworkNoBSDAttachKey is a property of IONetworkInterface objects. It has an OSBoolean value. @discussion Adding a property with this key and the value kOSBooleanTrue before the interface is published will hold off the BSD attach. When the interface is ready to attach to BSD, remove the property and then re-publish the interface by calling registerService(). */ #define kIONetworkNoBSDAttachKey "IONetworkNoBSDAttach" /*! @enum InterfaceObjectStates @discussion Constants used to encode the state of the interface object. @constant kIONetworkInterfaceRegisteredState The interface object has registered with the data link layer. @constant kIONetworkInterfaceOpenedState One or more clients have an open on the interface object. @constant kIONetworkInterfaceDisabledState The interface is temporarily unable to service its clients. This will occur when the network controller that is servicing the interface has entered a low power state that renders it unusable. */ enum { kIONetworkInterfaceRegisteredState = 0x1, kIONetworkInterfaceOpenedState = 0x2, kIONetworkInterfaceDisabledState = 0x4 }; #endif /* !_IONETWORKINTERFACE_H */
38
80
0.749103
4b0eb09a7d0c7cb910e3af24c295635cb3aafc30
6,349
h
C
FDPS-5.0g/src/particle_mesh/param.h
subarutaro/GPLUM
89b1dadb08a0c6adcdc48879ddf2b7b0fb02912f
[ "MIT" ]
77
2015-02-12T02:35:40.000Z
2022-03-11T01:10:31.000Z
FDPS-5.0g/src/particle_mesh/param.h
subarutaro/GPLUM
89b1dadb08a0c6adcdc48879ddf2b7b0fb02912f
[ "MIT" ]
9
2015-03-24T09:44:29.000Z
2021-11-30T19:42:58.000Z
FDPS-5.0g/src/particle_mesh/param.h
subarutaro/GPLUM
89b1dadb08a0c6adcdc48879ddf2b7b0fb02912f
[ "MIT" ]
28
2015-03-17T06:58:09.000Z
2022-02-14T07:16:25.000Z
#ifndef __PPPM__ #define __PPPM__ #include "openmp_param.h" #include "gadget_param.h" // A. Tanikawa add this. #include "param_fdps.h" namespace ParticleSimulator{ namespace ParticleMesh{ typedef const char *const cchar; /* Run ---------------------------------------------------------- */ //const int MAX_STEPS = 100000000; /* max steps for calculation */ const int MAX_STEPS = 0; /* max steps for calculation */ const double MAX_CPUTIME = 1e30; /* max cputime (second)*/ //const double Z_FIN = 0.0; const double Z_FIN = 1e30; cchar MODEL="Test"; cchar SNAPSHOT="Snapshot"; /* Tree ---------------------------------------------------------- */ const int NJMAX = 130000; /* j-particle buffer size (g5_get_jmemsize) */ const double Z_SWITCH_THETA = 5.0; /* redshift to switch opening angle */ #if 1 const double THETA_HIGHZ = 0.5; /* opening angle at high z*/ const double THETA = 0.5; /* opening angle */ #else const double THETA_HIGHZ = 0.0; /* opening angle at high z*/ const double THETA = 0.0; /* opening angle */ #endif const int NCRIT = 300; /* critical number of particles to share interaction list */ const int NLEAF = 10; /* minimum number of particle not to divide tree further */ // A. Tanikawa comments out this. const double CUTOFF_RADIUS = 3.0; /* Timestep ------------------------------------------------ */ const double Z_SWITCH_ETA = 0.0; const double ETA_HIGHZ = 0.3; /* accuracy parameter */ const double ETA_TIMESTEP = 0.3; /* accuracy parameter */ const double MAX_DLOGA = 0.03; const double constant_timestep = 5e-3; /* Softening ------------------------------------------------ */ const double CONST_Z_VALUE = 0.0; /* redshift to switch softening shape */ /* load balance ----------------------------------------------------------------------- */ const int LOADBALANCE_METHOD = 1; /* 0:interaction 1:pp+pm 2:n 3:1+lowerlimit 4:pp*/ const double SAMPLING_LOWER_LIMIT_FACTOR = 1.2; const int NRATE_EXCHANGE = 2500; /* sampling interval to decide area of each domain */ const int SORT_STEP = 10; /* step interval to sort particle using morton ordering */ const int nstep_smoothing_boundary = 5; const int nstep_decompose_x = 3; /* IO --------------------------------------------------------------------------*/ const int NUMBER_OF_COMM_PER_ALLTOALLV_FOR_INPUT_IC = 16; const int LOADBALANCELOG_ON = 0; const int BOUNDARYLOG_ON = 0; cchar STOPFILE = "stop"; const int fmerge = 2; cchar DUMPDIR = "Dump"; cchar DUMPDIR0 = "Dump0"; // for initial dump; cchar DUMPFILE = "dump"; const int ONELOGFLAG = 1; /* 0: each node outputs log 1: root node outputs log */ const int IO_CACHE_SIZE = 2097152; /* cache number of io (*3) */ /* Buffer ---------------------------------------------------------- */ const int CHARMAX = 256; const int MAXNNODE = 16384; const int MAXNNODE3 = MAXNNODE*3; const int NXMAX = 100; const int NSAMPMAX = 30000000; const int bufsize_largemem0 = 10000000; const int bufsize_largemem = 10000000; /* PM ---------------------------------------------------------- */ const int _ndiv_fft[3] = {2, 4, 2}; const int _pm_reduce_nx = 1; const int _pm_reduce_ny = 2; const int _pm_reduce_nz = 1; const int _flag_wisdom = 0; cchar FFTW_WISDOM_FILENAME_F = "wisdom_f"; cchar FFTW_WISDOM_FILENAME_B = "wisdom_b"; const int PMLOG_ON = 0; cchar PMLOG = "pm.log"; #ifdef FFT3D #ifndef RMM_PM #error #endif #ifndef FIX_FFTNODE #error #endif #endif /* Misc ---------------------------------------------------------- */ #define NOACC /* debug */ // A. Tanikawa comments out this. //#define UNIFORM /* uniform mass mode */ /*cannot use multi mass mode in the case of n>2^31 */ #define LONG_ID #define IDTYPE long long int #define MPI_IDTYPE MPI_LONG_LONG_INT cchar TORUSINFOFILE = "torus.dat"; #ifdef TREE2 #ifndef TREE_PARTICLE_CACHE #error #endif #endif /* on the fly analysis ---------------------------------------------------------- */ cchar IMAGEDIR = "Image"; /* relative path of image directory */ cchar NEWEST_IMAGEFILE = "newest.bmp"; const int IMAGESTEP = 32; /* step interval to output image (0:no output image) */ const int IMAGEWIDTH = 768; /* image width (px) */ const int IMAGEHEIGHT= 768; /* image height (px) */ const double IMAGEFACA = 1.098612; /* luminosity = s*(density-a) + b */ const double IMAGEFACB = 0.0; const double IMAGEFACS = 22.77958; const int COLORMAP = 0; /* others:gray 1:blue 2:red */ /* NUMBER_OF_PART_ALL -> number of particle of system */ /* NUMBER_OF_PART -> cache number to allocate particle array */ /* SIZE_OF_MESH -> number of mesh of pm part (2*NUMBER_OF_PART**(1/3))*/ /* SFT_FOR_PP -> softening parameter (ref evolve.c:get_eps) (1.0/(10*NUMBER_OF_PART**(1/3))) */ // A. Tanikawa defines this. #define N32_2H #ifdef N32_2H #define NUMBER_OF_PART_ALL (32768) #define NUMBER_OF_PART (32768) // A. Tanikawa comments out this. //#define SIZE_OF_MESH (16) #define SFT_FOR_PP (2.5e-4) #endif #ifdef N128_2H #define NUMBER_OF_PART_ALL (2097152) #define NUMBER_OF_PART (2097152) #define SIZE_OF_MESH (64) #define SFT_FOR_PP (2.5e-4) #endif #ifdef N256_H #define NUMBER_OF_PART_ALL (16777216) #define NUMBER_OF_PART (16777216) #define SIZE_OF_MESH (256) #define SFT_FOR_PP (2.5e-4) #endif #ifdef N256_2H #define NUMBER_OF_PART_ALL (16777216) #define NUMBER_OF_PART (16777216) #define SIZE_OF_MESH (128) #define SFT_FOR_PP (2.5e-4) #endif #ifdef N512_2H #define NUMBER_OF_PART_ALL (134217728) #define NUMBER_OF_PART (20000000) #define SIZE_OF_MESH (256) #define SFT_FOR_PP (6.25e-5) #endif #define SIZE_OF_MESH_P2 (SIZE_OF_MESH+2) #define SIZE_OF_GREEN (SIZE_OF_MESH/2+1) #define SFT_FOR_PM (CUTOFF_RADIUS/SIZE_OF_MESH) #define RADIUS_FOR_PP (SFT_FOR_PM) #define RADIUS_FOR_PP2 (RADIUS_FOR_PP*RADIUS_FOR_PP) #define _MIN_(a,b) ( ((a)<(b)) ? (a) : (b) ) #define _MAX_(a,b) ( ((a)>(b)) ? (a) : (b) ) const static long long int nleafmax = (long long int)NUMBER_OF_PART * (long long int)NLEAF / (long long int)NLEAF_PARALLEL_TREE_CONSTRUCTION; } // namespace ParticleMesh } // namespace ParticleSimulator #endif /* __PPPM__ */
30.233333
105
0.621358
b700c6e3fe3bbe0a8fa947bf8b275416105099d7
63,983
c
C
ruby-2.1.5/iseq.c
kongseokhwan/kulcloud-elk-sflow-logstash
80928788546d5d496f83897d56f8d33d99b264b6
[ "MIT" ]
null
null
null
ruby-2.1.5/iseq.c
kongseokhwan/kulcloud-elk-sflow-logstash
80928788546d5d496f83897d56f8d33d99b264b6
[ "MIT" ]
null
null
null
ruby-2.1.5/iseq.c
kongseokhwan/kulcloud-elk-sflow-logstash
80928788546d5d496f83897d56f8d33d99b264b6
[ "MIT" ]
null
null
null
/********************************************************************** iseq.c - $Author: nagachika $ created at: 2006-07-11(Tue) 09:00:03 +0900 Copyright (C) 2006 Koichi Sasada **********************************************************************/ #include "ruby/ruby.h" #include "internal.h" #include "eval_intern.h" /* #define RUBY_MARK_FREE_DEBUG 1 */ #include "gc.h" #include "vm_core.h" #include "iseq.h" #include "insns.inc" #include "insns_info.inc" #define ISEQ_MAJOR_VERSION 2 #define ISEQ_MINOR_VERSION 1 VALUE rb_cISeq; #define hidden_obj_p(obj) (!SPECIAL_CONST_P(obj) && !RBASIC(obj)->klass) static inline VALUE obj_resurrect(VALUE obj) { if (hidden_obj_p(obj)) { switch (BUILTIN_TYPE(obj)) { case T_STRING: obj = rb_str_resurrect(obj); break; case T_ARRAY: obj = rb_ary_resurrect(obj); break; } } return obj; } static void compile_data_free(struct iseq_compile_data *compile_data) { if (compile_data) { struct iseq_compile_data_storage *cur, *next; cur = compile_data->storage_head; while (cur) { next = cur->next; ruby_xfree(cur); cur = next; } ruby_xfree(compile_data); } } static void iseq_free(void *ptr) { rb_iseq_t *iseq; RUBY_FREE_ENTER("iseq"); if (ptr) { iseq = ptr; if (!iseq->orig) { /* It's possible that strings are freed */ if (0) { RUBY_GC_INFO("%s @ %s\n", RSTRING_PTR(iseq->location.label), RSTRING_PTR(iseq->location.path)); } if (iseq->iseq != iseq->iseq_encoded) { RUBY_FREE_UNLESS_NULL(iseq->iseq_encoded); } RUBY_FREE_UNLESS_NULL(iseq->iseq); RUBY_FREE_UNLESS_NULL(iseq->line_info_table); RUBY_FREE_UNLESS_NULL(iseq->local_table); RUBY_FREE_UNLESS_NULL(iseq->is_entries); RUBY_FREE_UNLESS_NULL(iseq->callinfo_entries); RUBY_FREE_UNLESS_NULL(iseq->catch_table); RUBY_FREE_UNLESS_NULL(iseq->arg_opt_table); RUBY_FREE_UNLESS_NULL(iseq->arg_keyword_table); compile_data_free(iseq->compile_data); } ruby_xfree(ptr); } RUBY_FREE_LEAVE("iseq"); } static void iseq_mark(void *ptr) { RUBY_MARK_ENTER("iseq"); if (ptr) { rb_iseq_t *iseq = ptr; RUBY_GC_INFO("%s @ %s\n", RSTRING_PTR(iseq->location.label), RSTRING_PTR(iseq->location.path)); RUBY_MARK_UNLESS_NULL(iseq->mark_ary); RUBY_MARK_UNLESS_NULL(iseq->location.label); RUBY_MARK_UNLESS_NULL(iseq->location.base_label); RUBY_MARK_UNLESS_NULL(iseq->location.path); RUBY_MARK_UNLESS_NULL(iseq->location.absolute_path); RUBY_MARK_UNLESS_NULL((VALUE)iseq->cref_stack); RUBY_MARK_UNLESS_NULL(iseq->klass); RUBY_MARK_UNLESS_NULL(iseq->coverage); RUBY_MARK_UNLESS_NULL(iseq->orig); if (iseq->compile_data != 0) { struct iseq_compile_data *const compile_data = iseq->compile_data; RUBY_MARK_UNLESS_NULL(compile_data->mark_ary); RUBY_MARK_UNLESS_NULL(compile_data->err_info); RUBY_MARK_UNLESS_NULL(compile_data->catch_table_ary); } } RUBY_MARK_LEAVE("iseq"); } static size_t iseq_memsize(const void *ptr) { size_t size = sizeof(rb_iseq_t); const rb_iseq_t *iseq; if (ptr) { iseq = ptr; if (!iseq->orig) { if (iseq->iseq != iseq->iseq_encoded) { size += iseq->iseq_size * sizeof(VALUE); } size += iseq->iseq_size * sizeof(VALUE); size += iseq->line_info_size * sizeof(struct iseq_line_info_entry); size += iseq->local_table_size * sizeof(ID); size += iseq->catch_table_size * sizeof(struct iseq_catch_table_entry); size += iseq->arg_opts * sizeof(VALUE); size += iseq->is_size * sizeof(union iseq_inline_storage_entry); size += iseq->callinfo_size * sizeof(rb_call_info_t); if (iseq->compile_data) { struct iseq_compile_data_storage *cur; cur = iseq->compile_data->storage_head; while (cur) { size += cur->size + sizeof(struct iseq_compile_data_storage); cur = cur->next; } size += sizeof(struct iseq_compile_data); } } } return size; } static const rb_data_type_t iseq_data_type = { "iseq", { iseq_mark, iseq_free, iseq_memsize, }, /* functions */ NULL, NULL, RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED }; static VALUE iseq_alloc(VALUE klass) { rb_iseq_t *iseq; return TypedData_Make_Struct(klass, rb_iseq_t, &iseq_data_type, iseq); } static rb_iseq_location_t * iseq_location_setup(rb_iseq_t *iseq, VALUE path, VALUE absolute_path, VALUE name, size_t first_lineno) { rb_iseq_location_t *loc = &iseq->location; RB_OBJ_WRITE(iseq->self, &loc->path, path); if (RTEST(absolute_path) && rb_str_cmp(path, absolute_path) == 0) { RB_OBJ_WRITE(iseq->self, &loc->absolute_path, path); } else { RB_OBJ_WRITE(iseq->self, &loc->absolute_path, absolute_path); } RB_OBJ_WRITE(iseq->self, &loc->label, name); RB_OBJ_WRITE(iseq->self, &loc->base_label, name); loc->first_lineno = first_lineno; return loc; } #define ISEQ_SET_CREF(iseq, cref) RB_OBJ_WRITE((iseq)->self, &(iseq)->cref_stack, (cref)) static void set_relation(rb_iseq_t *iseq, const VALUE parent) { const VALUE type = iseq->type; rb_thread_t *th = GET_THREAD(); rb_iseq_t *piseq; /* set class nest stack */ if (type == ISEQ_TYPE_TOP) { /* toplevel is private */ RB_OBJ_WRITE(iseq->self, &iseq->cref_stack, NEW_CREF(rb_cObject)); iseq->cref_stack->nd_refinements = Qnil; iseq->cref_stack->nd_visi = NOEX_PRIVATE; if (th->top_wrapper) { NODE *cref = NEW_CREF(th->top_wrapper); cref->nd_refinements = Qnil; cref->nd_visi = NOEX_PRIVATE; RB_OBJ_WRITE(cref, &cref->nd_next, iseq->cref_stack); ISEQ_SET_CREF(iseq, cref); } iseq->local_iseq = iseq; } else if (type == ISEQ_TYPE_METHOD || type == ISEQ_TYPE_CLASS) { ISEQ_SET_CREF(iseq, NEW_CREF(0)); /* place holder */ iseq->cref_stack->nd_refinements = Qnil; iseq->local_iseq = iseq; } else if (RTEST(parent)) { GetISeqPtr(parent, piseq); ISEQ_SET_CREF(iseq, piseq->cref_stack); iseq->local_iseq = piseq->local_iseq; } if (RTEST(parent)) { GetISeqPtr(parent, piseq); iseq->parent_iseq = piseq; } if (type == ISEQ_TYPE_MAIN) { iseq->local_iseq = iseq; } } void rb_iseq_add_mark_object(rb_iseq_t *iseq, VALUE obj) { if (!RTEST(iseq->mark_ary)) { RB_OBJ_WRITE(iseq->self, &iseq->mark_ary, rb_ary_tmp_new(3)); RBASIC_CLEAR_CLASS(iseq->mark_ary); } rb_ary_push(iseq->mark_ary, obj); } static VALUE prepare_iseq_build(rb_iseq_t *iseq, VALUE name, VALUE path, VALUE absolute_path, VALUE first_lineno, VALUE parent, enum iseq_type type, VALUE block_opt, const rb_compile_option_t *option) { iseq->type = type; iseq->arg_rest = -1; iseq->arg_block = -1; iseq->arg_keyword = -1; RB_OBJ_WRITE(iseq->self, &iseq->klass, 0); set_relation(iseq, parent); name = rb_fstring(name); path = rb_fstring(path); if (RTEST(absolute_path)) absolute_path = rb_fstring(absolute_path); iseq_location_setup(iseq, path, absolute_path, name, first_lineno); if (iseq != iseq->local_iseq) { RB_OBJ_WRITE(iseq->self, &iseq->location.base_label, iseq->local_iseq->location.label); } iseq->defined_method_id = 0; RB_OBJ_WRITE(iseq->self, &iseq->mark_ary, 0); /* * iseq->special_block_builder = GC_GUARDED_PTR_REF(block_opt); * iseq->cached_special_block_builder = 0; * iseq->cached_special_block = 0; */ iseq->compile_data = ALLOC(struct iseq_compile_data); MEMZERO(iseq->compile_data, struct iseq_compile_data, 1); RB_OBJ_WRITE(iseq->self, &iseq->compile_data->err_info, Qnil); RB_OBJ_WRITE(iseq->self, &iseq->compile_data->mark_ary, rb_ary_tmp_new(3)); iseq->compile_data->storage_head = iseq->compile_data->storage_current = (struct iseq_compile_data_storage *) ALLOC_N(char, INITIAL_ISEQ_COMPILE_DATA_STORAGE_BUFF_SIZE + sizeof(struct iseq_compile_data_storage)); RB_OBJ_WRITE(iseq->self, &iseq->compile_data->catch_table_ary, rb_ary_new()); iseq->compile_data->storage_head->pos = 0; iseq->compile_data->storage_head->next = 0; iseq->compile_data->storage_head->size = INITIAL_ISEQ_COMPILE_DATA_STORAGE_BUFF_SIZE; iseq->compile_data->storage_head->buff = (char *)(&iseq->compile_data->storage_head->buff + 1); iseq->compile_data->option = option; iseq->compile_data->last_coverable_line = -1; RB_OBJ_WRITE(iseq->self, &iseq->coverage, Qfalse); if (!GET_THREAD()->parse_in_eval) { VALUE coverages = rb_get_coverages(); if (RTEST(coverages)) { RB_OBJ_WRITE(iseq->self, &iseq->coverage, rb_hash_lookup(coverages, path)); if (NIL_P(iseq->coverage)) RB_OBJ_WRITE(iseq->self, &iseq->coverage, Qfalse); } } return Qtrue; } static VALUE cleanup_iseq_build(rb_iseq_t *iseq) { struct iseq_compile_data *data = iseq->compile_data; VALUE err = data->err_info; iseq->compile_data = 0; compile_data_free(data); if (RTEST(err)) { rb_funcall2(err, rb_intern("set_backtrace"), 1, &iseq->location.path); rb_exc_raise(err); } return Qtrue; } static rb_compile_option_t COMPILE_OPTION_DEFAULT = { OPT_INLINE_CONST_CACHE, /* int inline_const_cache; */ OPT_PEEPHOLE_OPTIMIZATION, /* int peephole_optimization; */ OPT_TAILCALL_OPTIMIZATION, /* int tailcall_optimization */ OPT_SPECIALISED_INSTRUCTION, /* int specialized_instruction; */ OPT_OPERANDS_UNIFICATION, /* int operands_unification; */ OPT_INSTRUCTIONS_UNIFICATION, /* int instructions_unification; */ OPT_STACK_CACHING, /* int stack_caching; */ OPT_TRACE_INSTRUCTION, /* int trace_instruction */ }; static const rb_compile_option_t COMPILE_OPTION_FALSE = {0}; static void make_compile_option(rb_compile_option_t *option, VALUE opt) { if (opt == Qnil) { *option = COMPILE_OPTION_DEFAULT; } else if (opt == Qfalse) { *option = COMPILE_OPTION_FALSE; } else if (opt == Qtrue) { int i; for (i = 0; i < (int)(sizeof(rb_compile_option_t) / sizeof(int)); ++i) ((int *)option)[i] = 1; } else if (CLASS_OF(opt) == rb_cHash) { *option = COMPILE_OPTION_DEFAULT; #define SET_COMPILE_OPTION(o, h, mem) \ { VALUE flag = rb_hash_aref((h), ID2SYM(rb_intern(#mem))); \ if (flag == Qtrue) { (o)->mem = 1; } \ else if (flag == Qfalse) { (o)->mem = 0; } \ } #define SET_COMPILE_OPTION_NUM(o, h, mem) \ { VALUE num = rb_hash_aref(opt, ID2SYM(rb_intern(#mem))); \ if (!NIL_P(num)) (o)->mem = NUM2INT(num); \ } SET_COMPILE_OPTION(option, opt, inline_const_cache); SET_COMPILE_OPTION(option, opt, peephole_optimization); SET_COMPILE_OPTION(option, opt, tailcall_optimization); SET_COMPILE_OPTION(option, opt, specialized_instruction); SET_COMPILE_OPTION(option, opt, operands_unification); SET_COMPILE_OPTION(option, opt, instructions_unification); SET_COMPILE_OPTION(option, opt, stack_caching); SET_COMPILE_OPTION(option, opt, trace_instruction); SET_COMPILE_OPTION_NUM(option, opt, debug_level); #undef SET_COMPILE_OPTION #undef SET_COMPILE_OPTION_NUM } else { rb_raise(rb_eTypeError, "Compile option must be Hash/true/false/nil"); } } static VALUE make_compile_option_value(rb_compile_option_t *option) { VALUE opt = rb_hash_new(); #define SET_COMPILE_OPTION(o, h, mem) \ rb_hash_aset((h), ID2SYM(rb_intern(#mem)), (o)->mem ? Qtrue : Qfalse) #define SET_COMPILE_OPTION_NUM(o, h, mem) \ rb_hash_aset((h), ID2SYM(rb_intern(#mem)), INT2NUM((o)->mem)) { SET_COMPILE_OPTION(option, opt, inline_const_cache); SET_COMPILE_OPTION(option, opt, peephole_optimization); SET_COMPILE_OPTION(option, opt, tailcall_optimization); SET_COMPILE_OPTION(option, opt, specialized_instruction); SET_COMPILE_OPTION(option, opt, operands_unification); SET_COMPILE_OPTION(option, opt, instructions_unification); SET_COMPILE_OPTION(option, opt, stack_caching); SET_COMPILE_OPTION(option, opt, trace_instruction); SET_COMPILE_OPTION_NUM(option, opt, debug_level); } #undef SET_COMPILE_OPTION #undef SET_COMPILE_OPTION_NUM return opt; } VALUE rb_iseq_new(NODE *node, VALUE name, VALUE path, VALUE absolute_path, VALUE parent, enum iseq_type type) { return rb_iseq_new_with_opt(node, name, path, absolute_path, INT2FIX(0), parent, type, &COMPILE_OPTION_DEFAULT); } VALUE rb_iseq_new_top(NODE *node, VALUE name, VALUE path, VALUE absolute_path, VALUE parent) { return rb_iseq_new_with_opt(node, name, path, absolute_path, INT2FIX(0), parent, ISEQ_TYPE_TOP, &COMPILE_OPTION_DEFAULT); } VALUE rb_iseq_new_main(NODE *node, VALUE path, VALUE absolute_path) { rb_thread_t *th = GET_THREAD(); VALUE parent = th->base_block->iseq->self; return rb_iseq_new_with_opt(node, rb_str_new2("<main>"), path, absolute_path, INT2FIX(0), parent, ISEQ_TYPE_MAIN, &COMPILE_OPTION_DEFAULT); } static VALUE rb_iseq_new_with_bopt_and_opt(NODE *node, VALUE name, VALUE path, VALUE absolute_path, VALUE first_lineno, VALUE parent, enum iseq_type type, VALUE bopt, const rb_compile_option_t *option) { rb_iseq_t *iseq; VALUE self = iseq_alloc(rb_cISeq); GetISeqPtr(self, iseq); iseq->self = self; prepare_iseq_build(iseq, name, path, absolute_path, first_lineno, parent, type, bopt, option); rb_iseq_compile_node(self, node); cleanup_iseq_build(iseq); return self; } VALUE rb_iseq_new_with_opt(NODE *node, VALUE name, VALUE path, VALUE absolute_path, VALUE first_lineno, VALUE parent, enum iseq_type type, const rb_compile_option_t *option) { /* TODO: argument check */ return rb_iseq_new_with_bopt_and_opt(node, name, path, absolute_path, first_lineno, parent, type, Qfalse, option); } VALUE rb_iseq_new_with_bopt(NODE *node, VALUE name, VALUE path, VALUE absolute_path, VALUE first_lineno, VALUE parent, enum iseq_type type, VALUE bopt) { /* TODO: argument check */ return rb_iseq_new_with_bopt_and_opt(node, name, path, absolute_path, first_lineno, parent, type, bopt, &COMPILE_OPTION_DEFAULT); } #define CHECK_ARRAY(v) rb_convert_type((v), T_ARRAY, "Array", "to_ary") #define CHECK_STRING(v) rb_convert_type((v), T_STRING, "String", "to_str") #define CHECK_SYMBOL(v) rb_convert_type((v), T_SYMBOL, "Symbol", "to_sym") static inline VALUE CHECK_INTEGER(VALUE v) {(void)NUM2LONG(v); return v;} static VALUE iseq_load(VALUE self, VALUE data, VALUE parent, VALUE opt) { VALUE iseqval = iseq_alloc(self); VALUE magic, version1, version2, format_type, misc; VALUE name, path, absolute_path, first_lineno; VALUE type, body, locals, args, exception; st_data_t iseq_type; static struct st_table *type_map_cache = 0; struct st_table *type_map = 0; rb_iseq_t *iseq; rb_compile_option_t option; int i = 0; /* [magic, major_version, minor_version, format_type, misc, * label, path, first_lineno, * type, locals, args, exception_table, body] */ data = CHECK_ARRAY(data); magic = CHECK_STRING(rb_ary_entry(data, i++)); version1 = CHECK_INTEGER(rb_ary_entry(data, i++)); version2 = CHECK_INTEGER(rb_ary_entry(data, i++)); format_type = CHECK_INTEGER(rb_ary_entry(data, i++)); misc = rb_ary_entry(data, i++); /* TODO */ ((void)magic, (void)version1, (void)version2, (void)format_type, (void)misc); name = CHECK_STRING(rb_ary_entry(data, i++)); path = CHECK_STRING(rb_ary_entry(data, i++)); absolute_path = rb_ary_entry(data, i++); absolute_path = NIL_P(absolute_path) ? Qnil : CHECK_STRING(absolute_path); first_lineno = CHECK_INTEGER(rb_ary_entry(data, i++)); type = CHECK_SYMBOL(rb_ary_entry(data, i++)); locals = CHECK_ARRAY(rb_ary_entry(data, i++)); args = rb_ary_entry(data, i++); if (FIXNUM_P(args) || (args = CHECK_ARRAY(args))) { /* */ } exception = CHECK_ARRAY(rb_ary_entry(data, i++)); body = CHECK_ARRAY(rb_ary_entry(data, i++)); GetISeqPtr(iseqval, iseq); iseq->self = iseqval; iseq->local_iseq = iseq; type_map = type_map_cache; if (type_map == 0) { struct st_table *cached_map; type_map = st_init_numtable(); st_insert(type_map, ID2SYM(rb_intern("top")), ISEQ_TYPE_TOP); st_insert(type_map, ID2SYM(rb_intern("method")), ISEQ_TYPE_METHOD); st_insert(type_map, ID2SYM(rb_intern("block")), ISEQ_TYPE_BLOCK); st_insert(type_map, ID2SYM(rb_intern("class")), ISEQ_TYPE_CLASS); st_insert(type_map, ID2SYM(rb_intern("rescue")), ISEQ_TYPE_RESCUE); st_insert(type_map, ID2SYM(rb_intern("ensure")), ISEQ_TYPE_ENSURE); st_insert(type_map, ID2SYM(rb_intern("eval")), ISEQ_TYPE_EVAL); st_insert(type_map, ID2SYM(rb_intern("main")), ISEQ_TYPE_MAIN); st_insert(type_map, ID2SYM(rb_intern("defined_guard")), ISEQ_TYPE_DEFINED_GUARD); cached_map = ATOMIC_PTR_CAS(type_map_cache, (struct st_table *)0, type_map); if (cached_map) { st_free_table(type_map); type_map = cached_map; } } if (st_lookup(type_map, type, &iseq_type) == 0) { ID typeid = SYM2ID(type); VALUE typename = rb_id2str(typeid); if (typename) rb_raise(rb_eTypeError, "unsupport type: :%"PRIsVALUE, typename); else rb_raise(rb_eTypeError, "unsupport type: %p", (void *)typeid); } if (parent == Qnil) { parent = 0; } make_compile_option(&option, opt); prepare_iseq_build(iseq, name, path, absolute_path, first_lineno, parent, (enum iseq_type)iseq_type, 0, &option); rb_iseq_build_from_ary(iseq, locals, args, exception, body); cleanup_iseq_build(iseq); return iseqval; } /* * :nodoc: */ static VALUE iseq_s_load(int argc, VALUE *argv, VALUE self) { VALUE data, opt=Qnil; rb_scan_args(argc, argv, "11", &data, &opt); return iseq_load(self, data, 0, opt); } VALUE rb_iseq_load(VALUE data, VALUE parent, VALUE opt) { return iseq_load(rb_cISeq, data, parent, opt); } VALUE rb_iseq_compile_with_option(VALUE src, VALUE file, VALUE absolute_path, VALUE line, rb_block_t *base_block, VALUE opt) { int state; rb_thread_t *th = GET_THREAD(); rb_block_t *prev_base_block = th->base_block; VALUE iseqval = Qundef; th->base_block = base_block; TH_PUSH_TAG(th); if ((state = EXEC_TAG()) == 0) { VALUE parser; int ln = NUM2INT(line); NODE *node; rb_compile_option_t option; StringValueCStr(file); make_compile_option(&option, opt); parser = rb_parser_new(); if (RB_TYPE_P((src), T_FILE)) node = rb_parser_compile_file_path(parser, file, src, ln); else { node = rb_parser_compile_string_path(parser, file, src, ln); if (!node) { rb_exc_raise(GET_THREAD()->errinfo); /* TODO: check err */ } } if (base_block && base_block->iseq) { iseqval = rb_iseq_new_with_opt(node, base_block->iseq->location.label, file, absolute_path, line, base_block->iseq->self, ISEQ_TYPE_EVAL, &option); } else { iseqval = rb_iseq_new_with_opt(node, rb_str_new2("<compiled>"), file, absolute_path, line, Qfalse, ISEQ_TYPE_TOP, &option); } } TH_POP_TAG(); th->base_block = prev_base_block; if (state) { JUMP_TAG(state); } return iseqval; } VALUE rb_iseq_compile(VALUE src, VALUE file, VALUE line) { return rb_iseq_compile_with_option(src, file, Qnil, line, 0, Qnil); } VALUE rb_iseq_compile_on_base(VALUE src, VALUE file, VALUE line, rb_block_t *base_block) { return rb_iseq_compile_with_option(src, file, Qnil, line, base_block, Qnil); } /* * call-seq: * InstructionSequence.compile(source[, file[, path[, line[, options]]]]) -> iseq * InstructionSequence.new(source[, file[, path[, line[, options]]]]) -> iseq * * Takes +source+, a String of Ruby code and compiles it to an * InstructionSequence. * * Optionally takes +file+, +path+, and +line+ which describe the filename, * absolute path and first line number of the ruby code in +source+ which are * metadata attached to the returned +iseq+. * * +options+, which can be +true+, +false+ or a +Hash+, is used to * modify the default behavior of the Ruby iseq compiler. * * For details regarding valid compile options see ::compile_option=. * * RubyVM::InstructionSequence.compile("a = 1 + 2") * #=> <RubyVM::InstructionSequence:<compiled>@<compiled>> * */ static VALUE iseq_s_compile(int argc, VALUE *argv, VALUE self) { VALUE src, file = Qnil, path = Qnil, line = INT2FIX(1), opt = Qnil; rb_secure(1); rb_scan_args(argc, argv, "14", &src, &file, &path, &line, &opt); if (NIL_P(file)) file = rb_str_new2("<compiled>"); if (NIL_P(line)) line = INT2FIX(1); return rb_iseq_compile_with_option(src, file, path, line, 0, opt); } /* * call-seq: * InstructionSequence.compile_file(file[, options]) -> iseq * * Takes +file+, a String with the location of a Ruby source file, reads, * parses and compiles the file, and returns +iseq+, the compiled * InstructionSequence with source location metadata set. * * Optionally takes +options+, which can be +true+, +false+ or a +Hash+, to * modify the default behavior of the Ruby iseq compiler. * * For details regarding valid compile options see ::compile_option=. * * # /tmp/hello.rb * puts "Hello, world!" * * # elsewhere * RubyVM::InstructionSequence.compile_file("/tmp/hello.rb") * #=> <RubyVM::InstructionSequence:<main>@/tmp/hello.rb> */ static VALUE iseq_s_compile_file(int argc, VALUE *argv, VALUE self) { VALUE file, line = INT2FIX(1), opt = Qnil; VALUE parser; VALUE f; NODE *node; const char *fname; rb_compile_option_t option; rb_secure(1); rb_scan_args(argc, argv, "11", &file, &opt); FilePathValue(file); fname = StringValueCStr(file); f = rb_file_open_str(file, "r"); parser = rb_parser_new(); node = rb_parser_compile_file(parser, fname, f, NUM2INT(line)); make_compile_option(&option, opt); return rb_iseq_new_with_opt(node, rb_str_new2("<main>"), file, rb_realpath_internal(Qnil, file, 1), line, Qfalse, ISEQ_TYPE_TOP, &option); } /* * call-seq: * InstructionSequence.compile_option = options * * Sets the default values for various optimizations in the Ruby iseq * compiler. * * Possible values for +options+ include +true+, which enables all options, * +false+ which disables all options, and +nil+ which leaves all options * unchanged. * * You can also pass a +Hash+ of +options+ that you want to change, any * options not present in the hash will be left unchanged. * * Possible option names (which are keys in +options+) which can be set to * +true+ or +false+ include: * * * +:inline_const_cache+ * * +:instructions_unification+ * * +:operands_unification+ * * +:peephole_optimization+ * * +:specialized_instruction+ * * +:stack_caching+ * * +:tailcall_optimization+ * * +:trace_instruction+ * * Additionally, +:debug_level+ can be set to an integer. * * These default options can be overwritten for a single run of the iseq * compiler by passing any of the above values as the +options+ parameter to * ::new, ::compile and ::compile_file. */ static VALUE iseq_s_compile_option_set(VALUE self, VALUE opt) { rb_compile_option_t option; rb_secure(1); make_compile_option(&option, opt); COMPILE_OPTION_DEFAULT = option; return opt; } /* * call-seq: * InstructionSequence.compile_option -> options * * Returns a hash of default options used by the Ruby iseq compiler. * * For details, see InstructionSequence.compile_option=. */ static VALUE iseq_s_compile_option_get(VALUE self) { return make_compile_option_value(&COMPILE_OPTION_DEFAULT); } static rb_iseq_t * iseq_check(VALUE val) { rb_iseq_t *iseq; GetISeqPtr(val, iseq); if (!iseq->location.label) { rb_raise(rb_eTypeError, "uninitialized InstructionSequence"); } return iseq; } /* * call-seq: * iseq.eval -> obj * * Evaluates the instruction sequence and returns the result. * * RubyVM::InstructionSequence.compile("1 + 2").eval #=> 3 */ static VALUE iseq_eval(VALUE self) { rb_secure(1); return rb_iseq_eval(self); } /* * Returns a human-readable string representation of this instruction * sequence, including the #label and #path. */ static VALUE iseq_inspect(VALUE self) { rb_iseq_t *iseq; GetISeqPtr(self, iseq); if (!iseq->location.label) { return rb_sprintf("#<%s: uninitialized>", rb_obj_classname(self)); } return rb_sprintf("<%s:%s@%s>", rb_obj_classname(self), RSTRING_PTR(iseq->location.label), RSTRING_PTR(iseq->location.path)); } /* * Returns the path of this instruction sequence. * * <code><compiled></code> if the iseq was evaluated from a string. * * For example, using irb: * * iseq = RubyVM::InstructionSequence.compile('num = 1 + 2') * #=> <RubyVM::InstructionSequence:<compiled>@<compiled>> * iseq.path * #=> "<compiled>" * * Using ::compile_file: * * # /tmp/method.rb * def hello * puts "hello, world" * end * * # in irb * > iseq = RubyVM::InstructionSequence.compile_file('/tmp/method.rb') * > iseq.path #=> /tmp/method.rb */ VALUE rb_iseq_path(VALUE self) { rb_iseq_t *iseq; GetISeqPtr(self, iseq); return iseq->location.path; } /* * Returns the absolute path of this instruction sequence. * * +nil+ if the iseq was evaluated from a string. * * For example, using ::compile_file: * * # /tmp/method.rb * def hello * puts "hello, world" * end * * # in irb * > iseq = RubyVM::InstructionSequence.compile_file('/tmp/method.rb') * > iseq.absolute_path #=> /tmp/method.rb */ VALUE rb_iseq_absolute_path(VALUE self) { rb_iseq_t *iseq; GetISeqPtr(self, iseq); return iseq->location.absolute_path; } /* Returns the label of this instruction sequence. * * <code><main></code> if it's at the top level, <code><compiled></code> if it * was evaluated from a string. * * For example, using irb: * * iseq = RubyVM::InstructionSequence.compile('num = 1 + 2') * #=> <RubyVM::InstructionSequence:<compiled>@<compiled>> * iseq.label * #=> "<compiled>" * * Using ::compile_file: * * # /tmp/method.rb * def hello * puts "hello, world" * end * * # in irb * > iseq = RubyVM::InstructionSequence.compile_file('/tmp/method.rb') * > iseq.label #=> <main> */ VALUE rb_iseq_label(VALUE self) { rb_iseq_t *iseq; GetISeqPtr(self, iseq); return iseq->location.label; } /* Returns the base label of this instruction sequence. * * For example, using irb: * * iseq = RubyVM::InstructionSequence.compile('num = 1 + 2') * #=> <RubyVM::InstructionSequence:<compiled>@<compiled>> * iseq.base_label * #=> "<compiled>" * * Using ::compile_file: * * # /tmp/method.rb * def hello * puts "hello, world" * end * * # in irb * > iseq = RubyVM::InstructionSequence.compile_file('/tmp/method.rb') * > iseq.base_label #=> <main> */ VALUE rb_iseq_base_label(VALUE self) { rb_iseq_t *iseq; GetISeqPtr(self, iseq); return iseq->location.base_label; } /* Returns the number of the first source line where the instruction sequence * was loaded from. * * For example, using irb: * * iseq = RubyVM::InstructionSequence.compile('num = 1 + 2') * #=> <RubyVM::InstructionSequence:<compiled>@<compiled>> * iseq.first_lineno * #=> 1 */ VALUE rb_iseq_first_lineno(VALUE self) { rb_iseq_t *iseq; GetISeqPtr(self, iseq); return iseq->location.first_lineno; } VALUE rb_iseq_klass(VALUE self) { rb_iseq_t *iseq; GetISeqPtr(self, iseq); return iseq->local_iseq->klass; } VALUE rb_iseq_method_name(VALUE self) { rb_iseq_t *iseq, *local_iseq; GetISeqPtr(self, iseq); local_iseq = iseq->local_iseq; if (local_iseq->type == ISEQ_TYPE_METHOD) { return local_iseq->location.base_label; } else { return Qnil; } } static VALUE iseq_data_to_ary(rb_iseq_t *iseq); /* * call-seq: * iseq.to_a -> ary * * Returns an Array with 14 elements representing the instruction sequence * with the following data: * * [magic] * A string identifying the data format. <b>Always * +YARVInstructionSequence/SimpleDataFormat+.</b> * * [major_version] * The major version of the instruction sequence. * * [minor_version] * The minor version of the instruction sequence. * * [format_type] * A number identifying the data format. <b>Always 1</b>. * * [misc] * A hash containing: * * [+:arg_size+] * the total number of arguments taken by the method or the block (0 if * _iseq_ doesn't represent a method or block) * [+:local_size+] * the number of local variables + 1 * [+:stack_max+] * used in calculating the stack depth at which a SystemStackError is * thrown. * * [#label] * The name of the context (block, method, class, module, etc.) that this * instruction sequence belongs to. * * <code><main></code> if it's at the top level, <code><compiled></code> if * it was evaluated from a string. * * [#path] * The relative path to the Ruby file where the instruction sequence was * loaded from. * * <code><compiled></code> if the iseq was evaluated from a string. * * [#absolute_path] * The absolute path to the Ruby file where the instruction sequence was * loaded from. * * +nil+ if the iseq was evaluated from a string. * * [#first_lineno] * The number of the first source line where the instruction sequence was * loaded from. * * [type] * The type of the instruction sequence. * * Valid values are +:top+, +:method+, +:block+, +:class+, +:rescue+, * +:ensure+, +:eval+, +:main+, and +:defined_guard+. * * [locals] * An array containing the names of all arguments and local variables as * symbols. * * [args] * The arity if the method or block only has required arguments. * * Otherwise an array of: * * [required_argc, [optional_arg_labels, ...], * splat_index, post_splat_argc, post_splat_index, * block_index, simple] * * More info about these values can be found in +vm_core.h+. * * [catch_table] * A list of exceptions and control flow operators (rescue, next, redo, * break, etc.). * * [bytecode] * An array of arrays containing the instruction names and operands that * make up the body of the instruction sequence. * */ static VALUE iseq_to_a(VALUE self) { rb_iseq_t *iseq = iseq_check(self); rb_secure(1); return iseq_data_to_ary(iseq); } /* TODO: search algorithm is brute force. this should be binary search or so. */ static struct iseq_line_info_entry * get_line_info(const rb_iseq_t *iseq, size_t pos) { size_t i = 0, size = iseq->line_info_size; struct iseq_line_info_entry *table = iseq->line_info_table; const int debug = 0; if (debug) { printf("size: %"PRIdSIZE"\n", size); printf("table[%"PRIdSIZE"]: position: %d, line: %d, pos: %"PRIdSIZE"\n", i, table[i].position, table[i].line_no, pos); } if (size == 0) { return 0; } else if (size == 1) { return &table[0]; } else { for (i=1; i<size; i++) { if (debug) printf("table[%"PRIdSIZE"]: position: %d, line: %d, pos: %"PRIdSIZE"\n", i, table[i].position, table[i].line_no, pos); if (table[i].position == pos) { return &table[i]; } if (table[i].position > pos) { return &table[i-1]; } } } return &table[i-1]; } static unsigned int find_line_no(const rb_iseq_t *iseq, size_t pos) { struct iseq_line_info_entry *entry = get_line_info(iseq, pos); if (entry) { return entry->line_no; } else { return 0; } } unsigned int rb_iseq_line_no(const rb_iseq_t *iseq, size_t pos) { if (pos == 0) { return find_line_no(iseq, pos); } else { return find_line_no(iseq, pos - 1); } } static VALUE id_to_name(ID id, VALUE default_value) { VALUE str = rb_id2str(id); if (!str) { str = default_value; } else if (!rb_str_symname_p(str)) { str = rb_str_inspect(str); } return str; } VALUE rb_insn_operand_intern(rb_iseq_t *iseq, VALUE insn, int op_no, VALUE op, int len, size_t pos, VALUE *pnop, VALUE child) { const char *types = insn_op_types(insn); char type = types[op_no]; VALUE ret; switch (type) { case TS_OFFSET: /* LONG */ ret = rb_sprintf("%"PRIdVALUE, (VALUE)(pos + len + op)); break; case TS_NUM: /* ULONG */ ret = rb_sprintf("%"PRIuVALUE, op); break; case TS_LINDEX:{ if (insn == BIN(getlocal) || insn == BIN(setlocal)) { if (pnop) { rb_iseq_t *diseq = iseq; VALUE level = *pnop, i; for (i = 0; i < level; i++) { diseq = diseq->parent_iseq; } ret = id_to_name(diseq->local_table[diseq->local_size - op], INT2FIX('*')); } else { ret = rb_sprintf("%"PRIuVALUE, op); } } else { ret = rb_inspect(INT2FIX(op)); } break; } case TS_ID: /* ID (symbol) */ op = ID2SYM(op); case TS_VALUE: /* VALUE */ op = obj_resurrect(op); ret = rb_inspect(op); if (CLASS_OF(op) == rb_cISeq) { if (child) { rb_ary_push(child, op); } } break; case TS_ISEQ: /* iseq */ { rb_iseq_t *iseq = (rb_iseq_t *)op; if (iseq) { ret = iseq->location.label; if (child) { rb_ary_push(child, iseq->self); } } else { ret = rb_str_new2("nil"); } break; } case TS_GENTRY: { struct rb_global_entry *entry = (struct rb_global_entry *)op; ret = rb_str_dup(rb_id2str(entry->id)); } break; case TS_IC: ret = rb_sprintf("<is:%"PRIdPTRDIFF">", (union iseq_inline_storage_entry *)op - iseq->is_entries); break; case TS_CALLINFO: { rb_call_info_t *ci = (rb_call_info_t *)op; VALUE ary = rb_ary_new(); if (ci->mid) { rb_ary_push(ary, rb_sprintf("mid:%s", rb_id2name(ci->mid))); } rb_ary_push(ary, rb_sprintf("argc:%d", ci->orig_argc)); if (ci->blockiseq) { if (child) { rb_ary_push(child, ci->blockiseq->self); } rb_ary_push(ary, rb_sprintf("block:%"PRIsVALUE, ci->blockiseq->location.label)); } if (ci->flag) { VALUE flags = rb_ary_new(); if (ci->flag & VM_CALL_ARGS_SPLAT) rb_ary_push(flags, rb_str_new2("ARGS_SPLAT")); if (ci->flag & VM_CALL_ARGS_BLOCKARG) rb_ary_push(flags, rb_str_new2("ARGS_BLOCKARG")); if (ci->flag & VM_CALL_FCALL) rb_ary_push(flags, rb_str_new2("FCALL")); if (ci->flag & VM_CALL_VCALL) rb_ary_push(flags, rb_str_new2("VCALL")); if (ci->flag & VM_CALL_TAILCALL) rb_ary_push(flags, rb_str_new2("TAILCALL")); if (ci->flag & VM_CALL_SUPER) rb_ary_push(flags, rb_str_new2("SUPER")); if (ci->flag & VM_CALL_OPT_SEND) rb_ary_push(flags, rb_str_new2("SNED")); /* maybe not reachable */ if (ci->flag & VM_CALL_ARGS_SKIP_SETUP) rb_ary_push(flags, rb_str_new2("ARGS_SKIP")); /* maybe not reachable */ rb_ary_push(ary, rb_ary_join(flags, rb_str_new2("|"))); } ret = rb_sprintf("<callinfo!%"PRIsVALUE">", rb_ary_join(ary, rb_str_new2(", "))); } break; case TS_CDHASH: ret = rb_str_new2("<cdhash>"); break; case TS_FUNCPTR: ret = rb_str_new2("<funcptr>"); break; default: rb_bug("insn_operand_intern: unknown operand type: %c", type); } return ret; } /** * Disassemble a instruction * Iseq -> Iseq inspect object */ int rb_iseq_disasm_insn(VALUE ret, VALUE *iseq, size_t pos, rb_iseq_t *iseqdat, VALUE child) { VALUE insn = iseq[pos]; int len = insn_len(insn); int j; const char *types = insn_op_types(insn); VALUE str = rb_str_new(0, 0); const char *insn_name_buff; insn_name_buff = insn_name(insn); if (1) { rb_str_catf(str, "%04"PRIdSIZE" %-16s ", pos, insn_name_buff); } else { rb_str_catf(str, "%04"PRIdSIZE" %-16.*s ", pos, (int)strcspn(insn_name_buff, "_"), insn_name_buff); } for (j = 0; types[j]; j++) { const char *types = insn_op_types(insn); VALUE opstr = rb_insn_operand_intern(iseqdat, insn, j, iseq[pos + j + 1], len, pos, &iseq[pos + j + 2], child); rb_str_concat(str, opstr); if (types[j + 1]) { rb_str_cat2(str, ", "); } } { unsigned int line_no = find_line_no(iseqdat, pos); unsigned int prev = pos == 0 ? 0 : find_line_no(iseqdat, pos - 1); if (line_no && line_no != prev) { long slen = RSTRING_LEN(str); slen = (slen > 70) ? 0 : (70 - slen); str = rb_str_catf(str, "%*s(%4d)", (int)slen, "", line_no); } } if (ret) { rb_str_cat2(str, "\n"); rb_str_concat(ret, str); } else { printf("%s\n", RSTRING_PTR(str)); } return len; } static const char * catch_type(int type) { switch (type) { case CATCH_TYPE_RESCUE: return "rescue"; case CATCH_TYPE_ENSURE: return "ensure"; case CATCH_TYPE_RETRY: return "retry"; case CATCH_TYPE_BREAK: return "break"; case CATCH_TYPE_REDO: return "redo"; case CATCH_TYPE_NEXT: return "next"; default: rb_bug("unknown catch type (%d)", type); return 0; } } /* * call-seq: * iseq.disasm -> str * iseq.disassemble -> str * * Returns the instruction sequence as a +String+ in human readable form. * * puts RubyVM::InstructionSequence.compile('1 + 2').disasm * * Produces: * * == disasm: <RubyVM::InstructionSequence:<compiled>@<compiled>>========== * 0000 trace 1 ( 1) * 0002 putobject 1 * 0004 putobject 2 * 0006 opt_plus <ic:1> * 0008 leave */ VALUE rb_iseq_disasm(VALUE self) { rb_iseq_t *iseqdat = iseq_check(self); VALUE *iseq; VALUE str = rb_str_new(0, 0); VALUE child = rb_ary_new(); unsigned long size; int i; long l; ID *tbl; size_t n; enum {header_minlen = 72}; rb_secure(1); iseq = iseqdat->iseq; size = iseqdat->iseq_size; rb_str_cat2(str, "== disasm: "); rb_str_concat(str, iseq_inspect(iseqdat->self)); if ((l = RSTRING_LEN(str)) < header_minlen) { rb_str_resize(str, header_minlen); memset(RSTRING_PTR(str) + l, '=', header_minlen - l); } rb_str_cat2(str, "\n"); /* show catch table information */ if (iseqdat->catch_table_size != 0) { rb_str_cat2(str, "== catch table\n"); } for (i = 0; i < iseqdat->catch_table_size; i++) { struct iseq_catch_table_entry *entry = &iseqdat->catch_table[i]; rb_str_catf(str, "| catch type: %-6s st: %04d ed: %04d sp: %04d cont: %04d\n", catch_type((int)entry->type), (int)entry->start, (int)entry->end, (int)entry->sp, (int)entry->cont); if (entry->iseq) { rb_str_concat(str, rb_iseq_disasm(entry->iseq)); } } if (iseqdat->catch_table_size != 0) { rb_str_cat2(str, "|-------------------------------------" "-----------------------------------\n"); } /* show local table information */ tbl = iseqdat->local_table; if (tbl) { rb_str_catf(str, "local table (size: %d, argc: %d " "[opts: %d, rest: %d, post: %d, block: %d, keyword: %d@%d] s%d)\n", iseqdat->local_size, iseqdat->argc, iseqdat->arg_opts, iseqdat->arg_rest, iseqdat->arg_post_len, iseqdat->arg_block, iseqdat->arg_keywords, iseqdat->local_size-iseqdat->arg_keyword, iseqdat->arg_simple); for (i = 0; i < iseqdat->local_table_size; i++) { long width; VALUE name = id_to_name(tbl[i], 0); char argi[0x100] = ""; char opti[0x100] = ""; if (iseqdat->arg_opts) { int argc = iseqdat->argc; int opts = iseqdat->arg_opts; if (i >= argc && i < argc + opts - 1) { snprintf(opti, sizeof(opti), "Opt=%"PRIdVALUE, iseqdat->arg_opt_table[i - argc]); } } snprintf(argi, sizeof(argi), "%s%s%s%s%s", /* arg, opts, rest, post block */ iseqdat->argc > i ? "Arg" : "", opti, iseqdat->arg_rest == i ? "Rest" : "", (iseqdat->arg_post_start <= i && i < iseqdat->arg_post_start + iseqdat->arg_post_len) ? "Post" : "", iseqdat->arg_block == i ? "Block" : ""); rb_str_catf(str, "[%2d] ", iseqdat->local_size - i); width = RSTRING_LEN(str) + 11; if (name) rb_str_append(str, name); else rb_str_cat2(str, "?"); if (*argi) rb_str_catf(str, "<%s>", argi); if ((width -= RSTRING_LEN(str)) > 0) rb_str_catf(str, "%*s", (int)width, ""); } rb_str_cat2(str, "\n"); } /* show each line */ for (n = 0; n < size;) { n += rb_iseq_disasm_insn(str, iseq, n, iseqdat, child); } for (i = 0; i < RARRAY_LEN(child); i++) { VALUE isv = rb_ary_entry(child, i); rb_str_concat(str, rb_iseq_disasm(isv)); } return str; } /* * Returns the instruction sequence containing the given proc or method. * * For example, using irb: * * # a proc * > p = proc { num = 1 + 2 } * > RubyVM::InstructionSequence.of(p) * > #=> <RubyVM::InstructionSequence:block in irb_binding@(irb)> * * # for a method * > def foo(bar); puts bar; end * > RubyVM::InstructionSequence.of(method(:foo)) * > #=> <RubyVM::InstructionSequence:foo@(irb)> * * Using ::compile_file: * * # /tmp/iseq_of.rb * def hello * puts "hello, world" * end * * $a_global_proc = proc { str = 'a' + 'b' } * * # in irb * > require '/tmp/iseq_of.rb' * * # first the method hello * > RubyVM::InstructionSequence.of(method(:hello)) * > #=> #<RubyVM::InstructionSequence:0x007fb73d7cb1d0> * * # then the global proc * > RubyVM::InstructionSequence.of($a_global_proc) * > #=> #<RubyVM::InstructionSequence:0x007fb73d7caf78> */ static VALUE iseq_s_of(VALUE klass, VALUE body) { VALUE ret = Qnil; rb_iseq_t *iseq; rb_secure(1); if (rb_obj_is_proc(body)) { rb_proc_t *proc; GetProcPtr(body, proc); iseq = proc->block.iseq; if (RUBY_VM_NORMAL_ISEQ_P(iseq)) { ret = iseq->self; } } else if ((iseq = rb_method_get_iseq(body)) != 0) { ret = iseq->self; } return ret; } /* * call-seq: * InstructionSequence.disasm(body) -> str * InstructionSequence.disassemble(body) -> str * * Takes +body+, a Method or Proc object, and returns a String with the * human readable instructions for +body+. * * For a Method object: * * # /tmp/method.rb * def hello * puts "hello, world" * end * * puts RubyVM::InstructionSequence.disasm(method(:hello)) * * Produces: * * == disasm: <RubyVM::InstructionSequence:hello@/tmp/method.rb>============ * 0000 trace 8 ( 1) * 0002 trace 1 ( 2) * 0004 putself * 0005 putstring "hello, world" * 0007 send :puts, 1, nil, 8, <ic:0> * 0013 trace 16 ( 3) * 0015 leave ( 2) * * For a Proc: * * # /tmp/proc.rb * p = proc { num = 1 + 2 } * puts RubyVM::InstructionSequence.disasm(p) * * Produces: * * == disasm: <RubyVM::InstructionSequence:block in <main>@/tmp/proc.rb>=== * == catch table * | catch type: redo st: 0000 ed: 0012 sp: 0000 cont: 0000 * | catch type: next st: 0000 ed: 0012 sp: 0000 cont: 0012 * |------------------------------------------------------------------------ * local table (size: 2, argc: 0 [opts: 0, rest: -1, post: 0, block: -1] s1) * [ 2] num * 0000 trace 1 ( 1) * 0002 putobject 1 * 0004 putobject 2 * 0006 opt_plus <ic:1> * 0008 dup * 0009 setlocal num, 0 * 0012 leave * */ static VALUE iseq_s_disasm(VALUE klass, VALUE body) { VALUE iseqval = iseq_s_of(klass, body); return NIL_P(iseqval) ? Qnil : rb_iseq_disasm(iseqval); } const char * ruby_node_name(int node) { switch (node) { #include "node_name.inc" default: rb_bug("unknown node (%d)", node); return 0; } } #define DECL_SYMBOL(name) \ static VALUE sym_##name #define INIT_SYMBOL(name) \ sym_##name = ID2SYM(rb_intern(#name)) static VALUE register_label(struct st_table *table, unsigned long idx) { VALUE sym; char buff[8 + (sizeof(idx) * CHAR_BIT * 32 / 100)]; snprintf(buff, sizeof(buff), "label_%lu", idx); sym = ID2SYM(rb_intern(buff)); st_insert(table, idx, sym); return sym; } static VALUE exception_type2symbol(VALUE type) { ID id; switch (type) { case CATCH_TYPE_RESCUE: CONST_ID(id, "rescue"); break; case CATCH_TYPE_ENSURE: CONST_ID(id, "ensure"); break; case CATCH_TYPE_RETRY: CONST_ID(id, "retry"); break; case CATCH_TYPE_BREAK: CONST_ID(id, "break"); break; case CATCH_TYPE_REDO: CONST_ID(id, "redo"); break; case CATCH_TYPE_NEXT: CONST_ID(id, "next"); break; default: rb_bug("..."); } return ID2SYM(id); } static int cdhash_each(VALUE key, VALUE value, VALUE ary) { rb_ary_push(ary, obj_resurrect(key)); rb_ary_push(ary, value); return ST_CONTINUE; } static VALUE iseq_data_to_ary(rb_iseq_t *iseq) { long i; size_t ti; unsigned int pos; unsigned int line = 0; VALUE *seq; VALUE val = rb_ary_new(); VALUE type; /* Symbol */ VALUE locals = rb_ary_new(); VALUE args = rb_ary_new(); VALUE body = rb_ary_new(); /* [[:insn1, ...], ...] */ VALUE nbody; VALUE exception = rb_ary_new(); /* [[....]] */ VALUE misc = rb_hash_new(); static VALUE insn_syms[VM_INSTRUCTION_SIZE]; struct st_table *labels_table = st_init_numtable(); DECL_SYMBOL(top); DECL_SYMBOL(method); DECL_SYMBOL(block); DECL_SYMBOL(class); DECL_SYMBOL(rescue); DECL_SYMBOL(ensure); DECL_SYMBOL(eval); DECL_SYMBOL(main); DECL_SYMBOL(defined_guard); if (sym_top == 0) { int i; for (i=0; i<VM_INSTRUCTION_SIZE; i++) { insn_syms[i] = ID2SYM(rb_intern(insn_name(i))); } INIT_SYMBOL(top); INIT_SYMBOL(method); INIT_SYMBOL(block); INIT_SYMBOL(class); INIT_SYMBOL(rescue); INIT_SYMBOL(ensure); INIT_SYMBOL(eval); INIT_SYMBOL(main); INIT_SYMBOL(defined_guard); } /* type */ switch (iseq->type) { case ISEQ_TYPE_TOP: type = sym_top; break; case ISEQ_TYPE_METHOD: type = sym_method; break; case ISEQ_TYPE_BLOCK: type = sym_block; break; case ISEQ_TYPE_CLASS: type = sym_class; break; case ISEQ_TYPE_RESCUE: type = sym_rescue; break; case ISEQ_TYPE_ENSURE: type = sym_ensure; break; case ISEQ_TYPE_EVAL: type = sym_eval; break; case ISEQ_TYPE_MAIN: type = sym_main; break; case ISEQ_TYPE_DEFINED_GUARD: type = sym_defined_guard; break; default: rb_bug("unsupported iseq type"); }; /* locals */ for (i=0; i<iseq->local_table_size; i++) { ID lid = iseq->local_table[i]; if (lid) { if (rb_id2str(lid)) rb_ary_push(locals, ID2SYM(lid)); } else { rb_ary_push(locals, ID2SYM(rb_intern("#arg_rest"))); } } /* args */ { /* * [argc, # argc * [label1, label2, ...] # opts * rest index, * post_len * post_start * block index, * simple, * ] */ VALUE arg_opt_labels = rb_ary_new(); int j; for (j=0; j<iseq->arg_opts; j++) { rb_ary_push(arg_opt_labels, register_label(labels_table, iseq->arg_opt_table[j])); } /* commit */ if (iseq->arg_simple == 1) { args = INT2FIX(iseq->argc); } else { rb_ary_push(args, INT2FIX(iseq->argc)); rb_ary_push(args, arg_opt_labels); rb_ary_push(args, INT2FIX(iseq->arg_post_len)); rb_ary_push(args, INT2FIX(iseq->arg_post_start)); rb_ary_push(args, INT2FIX(iseq->arg_rest)); rb_ary_push(args, INT2FIX(iseq->arg_block)); rb_ary_push(args, INT2FIX(iseq->arg_simple)); } } /* body */ for (seq = iseq->iseq; seq < iseq->iseq + iseq->iseq_size; ) { VALUE insn = *seq++; int j, len = insn_len(insn); VALUE *nseq = seq + len - 1; VALUE ary = rb_ary_new2(len); rb_ary_push(ary, insn_syms[insn]); for (j=0; j<len-1; j++, seq++) { switch (insn_op_type(insn, j)) { case TS_OFFSET: { unsigned long idx = nseq - iseq->iseq + *seq; rb_ary_push(ary, register_label(labels_table, idx)); break; } case TS_LINDEX: case TS_NUM: rb_ary_push(ary, INT2FIX(*seq)); break; case TS_VALUE: rb_ary_push(ary, obj_resurrect(*seq)); break; case TS_ISEQ: { rb_iseq_t *iseq = (rb_iseq_t *)*seq; if (iseq) { VALUE val = iseq_data_to_ary(iseq); rb_ary_push(ary, val); } else { rb_ary_push(ary, Qnil); } } break; case TS_GENTRY: { struct rb_global_entry *entry = (struct rb_global_entry *)*seq; rb_ary_push(ary, ID2SYM(entry->id)); } break; case TS_IC: { union iseq_inline_storage_entry *is = (union iseq_inline_storage_entry *)*seq; rb_ary_push(ary, INT2FIX(is - iseq->is_entries)); } break; case TS_CALLINFO: { rb_call_info_t *ci = (rb_call_info_t *)*seq; VALUE e = rb_hash_new(); rb_hash_aset(e, ID2SYM(rb_intern("mid")), ci->mid ? ID2SYM(ci->mid) : Qnil); rb_hash_aset(e, ID2SYM(rb_intern("flag")), ULONG2NUM(ci->flag)); rb_hash_aset(e, ID2SYM(rb_intern("orig_argc")), INT2FIX(ci->orig_argc)); rb_hash_aset(e, ID2SYM(rb_intern("blockptr")), ci->blockiseq ? iseq_data_to_ary(ci->blockiseq) : Qnil); rb_ary_push(ary, e); } break; case TS_ID: rb_ary_push(ary, ID2SYM(*seq)); break; case TS_CDHASH: { VALUE hash = *seq; VALUE val = rb_ary_new(); int i; rb_hash_foreach(hash, cdhash_each, val); for (i=0; i<RARRAY_LEN(val); i+=2) { VALUE pos = FIX2INT(rb_ary_entry(val, i+1)); unsigned long idx = nseq - iseq->iseq + pos; rb_ary_store(val, i+1, register_label(labels_table, idx)); } rb_ary_push(ary, val); } break; default: rb_bug("unknown operand: %c", insn_op_type(insn, j)); } } rb_ary_push(body, ary); } nbody = body; /* exception */ for (i=0; i<iseq->catch_table_size; i++) { VALUE ary = rb_ary_new(); struct iseq_catch_table_entry *entry = &iseq->catch_table[i]; rb_ary_push(ary, exception_type2symbol(entry->type)); if (entry->iseq) { rb_iseq_t *eiseq; GetISeqPtr(entry->iseq, eiseq); rb_ary_push(ary, iseq_data_to_ary(eiseq)); } else { rb_ary_push(ary, Qnil); } rb_ary_push(ary, register_label(labels_table, entry->start)); rb_ary_push(ary, register_label(labels_table, entry->end)); rb_ary_push(ary, register_label(labels_table, entry->cont)); rb_ary_push(ary, INT2FIX(entry->sp)); rb_ary_push(exception, ary); } /* make body with labels and insert line number */ body = rb_ary_new(); ti = 0; for (i=0, pos=0; i<RARRAY_LEN(nbody); i++) { VALUE ary = RARRAY_AREF(nbody, i); st_data_t label; if (st_lookup(labels_table, pos, &label)) { rb_ary_push(body, (VALUE)label); } if (ti < iseq->line_info_size && iseq->line_info_table[ti].position == pos) { line = iseq->line_info_table[ti].line_no; rb_ary_push(body, INT2FIX(line)); ti++; } rb_ary_push(body, ary); pos += RARRAY_LENINT(ary); /* reject too huge data */ } st_free_table(labels_table); rb_hash_aset(misc, ID2SYM(rb_intern("arg_size")), INT2FIX(iseq->arg_size)); rb_hash_aset(misc, ID2SYM(rb_intern("local_size")), INT2FIX(iseq->local_size)); rb_hash_aset(misc, ID2SYM(rb_intern("stack_max")), INT2FIX(iseq->stack_max)); /* TODO: compatibility issue */ /* * [:magic, :major_version, :minor_version, :format_type, :misc, * :name, :path, :absolute_path, :start_lineno, :type, :locals, :args, * :catch_table, :bytecode] */ rb_ary_push(val, rb_str_new2("YARVInstructionSequence/SimpleDataFormat")); rb_ary_push(val, INT2FIX(ISEQ_MAJOR_VERSION)); /* major */ rb_ary_push(val, INT2FIX(ISEQ_MINOR_VERSION)); /* minor */ rb_ary_push(val, INT2FIX(1)); rb_ary_push(val, misc); rb_ary_push(val, iseq->location.label); rb_ary_push(val, iseq->location.path); rb_ary_push(val, iseq->location.absolute_path); rb_ary_push(val, iseq->location.first_lineno); rb_ary_push(val, type); rb_ary_push(val, locals); rb_ary_push(val, args); rb_ary_push(val, exception); rb_ary_push(val, body); return val; } VALUE rb_iseq_clone(VALUE iseqval, VALUE newcbase) { VALUE newiseq = iseq_alloc(rb_cISeq); rb_iseq_t *iseq0, *iseq1; GetISeqPtr(iseqval, iseq0); GetISeqPtr(newiseq, iseq1); MEMCPY(iseq1, iseq0, rb_iseq_t, 1); /* TODO: write barrier? */ iseq1->self = newiseq; if (!iseq1->orig) { RB_OBJ_WRITE(iseq1->self, &iseq1->orig, iseqval); } if (iseq0->local_iseq == iseq0) { iseq1->local_iseq = iseq1; } if (newcbase) { ISEQ_SET_CREF(iseq1, NEW_CREF(newcbase)); RB_OBJ_WRITE(iseq1->cref_stack, &iseq1->cref_stack->nd_refinements, iseq0->cref_stack->nd_refinements); iseq1->cref_stack->nd_visi = iseq0->cref_stack->nd_visi; if (iseq0->cref_stack->nd_next) { RB_OBJ_WRITE(iseq1->cref_stack, &iseq1->cref_stack->nd_next, iseq0->cref_stack->nd_next); } RB_OBJ_WRITE(iseq1->self, &iseq1->klass, newcbase); } return newiseq; } VALUE rb_iseq_parameters(const rb_iseq_t *iseq, int is_proc) { int i, r; VALUE a, args = rb_ary_new2(iseq->arg_size); ID req, opt, rest, block, key, keyrest; #define PARAM_TYPE(type) rb_ary_push(a = rb_ary_new2(2), ID2SYM(type)) #define PARAM_ID(i) iseq->local_table[(i)] #define PARAM(i, type) ( \ PARAM_TYPE(type), \ rb_id2str(PARAM_ID(i)) ? \ rb_ary_push(a, ID2SYM(PARAM_ID(i))) : \ a) CONST_ID(req, "req"); CONST_ID(opt, "opt"); if (is_proc) { for (i = 0; i < iseq->argc; i++) { PARAM_TYPE(opt); rb_ary_push(a, rb_id2str(PARAM_ID(i)) ? ID2SYM(PARAM_ID(i)) : Qnil); rb_ary_push(args, a); } } else { for (i = 0; i < iseq->argc; i++) { rb_ary_push(args, PARAM(i, req)); } } r = iseq->argc + iseq->arg_opts - 1; for (; i < r; i++) { PARAM_TYPE(opt); if (rb_id2str(PARAM_ID(i))) { rb_ary_push(a, ID2SYM(PARAM_ID(i))); } rb_ary_push(args, a); } if (iseq->arg_rest != -1) { CONST_ID(rest, "rest"); rb_ary_push(args, PARAM(iseq->arg_rest, rest)); } r = iseq->arg_post_start + iseq->arg_post_len; if (is_proc) { for (i = iseq->arg_post_start; i < r; i++) { PARAM_TYPE(opt); rb_ary_push(a, rb_id2str(PARAM_ID(i)) ? ID2SYM(PARAM_ID(i)) : Qnil); rb_ary_push(args, a); } } else { for (i = iseq->arg_post_start; i < r; i++) { rb_ary_push(args, PARAM(i, req)); } } if (iseq->arg_keyword != -1) { i = 0; if (iseq->arg_keyword_required) { ID keyreq; CONST_ID(keyreq, "keyreq"); for (; i < iseq->arg_keyword_required; i++) { PARAM_TYPE(keyreq); if (rb_id2str(iseq->arg_keyword_table[i])) { rb_ary_push(a, ID2SYM(iseq->arg_keyword_table[i])); } rb_ary_push(args, a); } } CONST_ID(key, "key"); for (; i < iseq->arg_keywords; i++) { PARAM_TYPE(key); if (rb_id2str(iseq->arg_keyword_table[i])) { rb_ary_push(a, ID2SYM(iseq->arg_keyword_table[i])); } rb_ary_push(args, a); } if (!iseq->arg_keyword_check) { CONST_ID(keyrest, "keyrest"); rb_ary_push(args, PARAM(iseq->arg_keyword, keyrest)); } } if (iseq->arg_block != -1) { CONST_ID(block, "block"); rb_ary_push(args, PARAM(iseq->arg_block, block)); } return args; } VALUE rb_iseq_defined_string(enum defined_type type) { static const char expr_names[][18] = { "nil", "instance-variable", "local-variable", "global-variable", "class variable", "constant", "method", "yield", "super", "self", "true", "false", "assignment", "expression", }; const char *estr; VALUE *defs, str; if ((unsigned)(type - 1) >= (unsigned)numberof(expr_names)) return 0; estr = expr_names[type - 1]; if (!estr[0]) return 0; defs = GET_VM()->defined_strings; if (!defs) { defs = ruby_xcalloc(numberof(expr_names), sizeof(VALUE)); GET_VM()->defined_strings = defs; } str = defs[type-1]; if (!str) { str = rb_str_new_cstr(estr);; OBJ_FREEZE(str); defs[type-1] = str; } return str; } /* ruby2cext */ VALUE rb_iseq_build_for_ruby2cext( const rb_iseq_t *iseq_template, const rb_insn_func_t *func, const struct iseq_line_info_entry *line_info_table, const char **local_table, const VALUE *arg_opt_table, const struct iseq_catch_table_entry *catch_table, const char *name, const char *path, const unsigned short first_lineno) { unsigned long i; VALUE iseqval = iseq_alloc(rb_cISeq); rb_iseq_t *iseq; GetISeqPtr(iseqval, iseq); /* copy iseq */ MEMCPY(iseq, iseq_template, rb_iseq_t, 1); /* TODO: write barrier, *iseq = *iseq_template; */ RB_OBJ_WRITE(iseq->self, &iseq->location.label, rb_str_new2(name)); RB_OBJ_WRITE(iseq->self, &iseq->location.path, rb_str_new2(path)); iseq->location.first_lineno = first_lineno; RB_OBJ_WRITE(iseq->self, &iseq->mark_ary, 0); iseq->self = iseqval; iseq->iseq = ALLOC_N(VALUE, iseq->iseq_size); for (i=0; i<iseq->iseq_size; i+=2) { iseq->iseq[i] = BIN(opt_call_c_function); iseq->iseq[i+1] = (VALUE)func; } rb_iseq_translate_threaded_code(iseq); #define ALLOC_AND_COPY(dst, src, type, size) do { \ if (size) { \ (dst) = ALLOC_N(type, (size)); \ MEMCPY((dst), (src), type, (size)); \ } \ } while (0) ALLOC_AND_COPY(iseq->line_info_table, line_info_table, struct iseq_line_info_entry, iseq->line_info_size); ALLOC_AND_COPY(iseq->catch_table, catch_table, struct iseq_catch_table_entry, iseq->catch_table_size); ALLOC_AND_COPY(iseq->arg_opt_table, arg_opt_table, VALUE, iseq->arg_opts); set_relation(iseq, 0); return iseqval; } /* Experimental tracing support: trace(line) -> trace(specified_line) * MRI Specific. */ int rb_iseq_line_trace_each(VALUE iseqval, int (*func)(int line, rb_event_flag_t *events_ptr, void *d), void *data) { int trace_num = 0; size_t pos, insn; rb_iseq_t *iseq; int cont = 1; GetISeqPtr(iseqval, iseq); for (pos = 0; cont && pos < iseq->iseq_size; pos += insn_len(insn)) { insn = iseq->iseq[pos]; if (insn == BIN(trace)) { rb_event_flag_t current_events = (VALUE)iseq->iseq[pos+1]; if (current_events & RUBY_EVENT_LINE) { rb_event_flag_t events = current_events & RUBY_EVENT_SPECIFIED_LINE; trace_num++; if (func) { int line = find_line_no(iseq, pos); /* printf("line: %d\n", line); */ cont = (*func)(line, &events, data); if (current_events != events) { iseq->iseq[pos+1] = iseq->iseq_encoded[pos+1] = (VALUE)(current_events | (events & RUBY_EVENT_SPECIFIED_LINE)); } } } } } return trace_num; } static int collect_trace(int line, rb_event_flag_t *events_ptr, void *ptr) { VALUE result = (VALUE)ptr; rb_ary_push(result, INT2NUM(line)); return 1; } /* * <b>Experimental MRI specific feature, only available as C level api.</b> * * Returns all +specified_line+ events. */ VALUE rb_iseq_line_trace_all(VALUE iseqval) { VALUE result = rb_ary_new(); rb_iseq_line_trace_each(iseqval, collect_trace, (void *)result); return result; } struct set_specifc_data { int pos; int set; int prev; /* 1: set, 2: unset, 0: not found */ }; static int line_trace_specify(int line, rb_event_flag_t *events_ptr, void *ptr) { struct set_specifc_data *data = (struct set_specifc_data *)ptr; if (data->pos == 0) { data->prev = *events_ptr & RUBY_EVENT_SPECIFIED_LINE ? 1 : 2; if (data->set) { *events_ptr = *events_ptr | RUBY_EVENT_SPECIFIED_LINE; } else { *events_ptr = *events_ptr & ~RUBY_EVENT_SPECIFIED_LINE; } return 0; /* found */ } else { data->pos--; return 1; } } /* * <b>Experimental MRI specific feature, only available as C level api.</b> * * Set a +specified_line+ event at the given line position, if the +set+ * parameter is +true+. * * This method is useful for building a debugger breakpoint at a specific line. * * A TypeError is raised if +set+ is not boolean. * * If +pos+ is a negative integer a TypeError exception is raised. */ VALUE rb_iseq_line_trace_specify(VALUE iseqval, VALUE pos, VALUE set) { struct set_specifc_data data; data.prev = 0; data.pos = NUM2INT(pos); if (data.pos < 0) rb_raise(rb_eTypeError, "`pos' is negative"); switch (set) { case Qtrue: data.set = 1; break; case Qfalse: data.set = 0; break; default: rb_raise(rb_eTypeError, "`set' should be true/false"); } rb_iseq_line_trace_each(iseqval, line_trace_specify, (void *)&data); if (data.prev == 0) { rb_raise(rb_eTypeError, "`pos' is out of range."); } return data.prev == 1 ? Qtrue : Qfalse; } /* * Document-class: RubyVM::InstructionSequence * * The InstructionSequence class represents a compiled sequence of * instructions for the Ruby Virtual Machine. * * With it, you can get a handle to the instructions that make up a method or * a proc, compile strings of Ruby code down to VM instructions, and * disassemble instruction sequences to strings for easy inspection. It is * mostly useful if you want to learn how the Ruby VM works, but it also lets * you control various settings for the Ruby iseq compiler. * * You can find the source for the VM instructions in +insns.def+ in the Ruby * source. * * The instruction sequence results will almost certainly change as Ruby * changes, so example output in this documentation may be different from what * you see. */ void Init_ISeq(void) { /* declare ::RubyVM::InstructionSequence */ rb_cISeq = rb_define_class_under(rb_cRubyVM, "InstructionSequence", rb_cObject); rb_define_alloc_func(rb_cISeq, iseq_alloc); rb_define_method(rb_cISeq, "inspect", iseq_inspect, 0); rb_define_method(rb_cISeq, "disasm", rb_iseq_disasm, 0); rb_define_method(rb_cISeq, "disassemble", rb_iseq_disasm, 0); rb_define_method(rb_cISeq, "to_a", iseq_to_a, 0); rb_define_method(rb_cISeq, "eval", iseq_eval, 0); /* location APIs */ rb_define_method(rb_cISeq, "path", rb_iseq_path, 0); rb_define_method(rb_cISeq, "absolute_path", rb_iseq_absolute_path, 0); rb_define_method(rb_cISeq, "label", rb_iseq_label, 0); rb_define_method(rb_cISeq, "base_label", rb_iseq_base_label, 0); rb_define_method(rb_cISeq, "first_lineno", rb_iseq_first_lineno, 0); #if 0 /* Now, it is experimental. No discussions, no tests. */ /* They can be used from C level. Please give us feedback. */ rb_define_method(rb_cISeq, "line_trace_all", rb_iseq_line_trace_all, 0); rb_define_method(rb_cISeq, "line_trace_specify", rb_iseq_line_trace_specify, 2); #else (void)rb_iseq_line_trace_all; (void)rb_iseq_line_trace_specify; #endif #if 0 /* TBD */ rb_define_private_method(rb_cISeq, "marshal_dump", iseq_marshal_dump, 0); rb_define_private_method(rb_cISeq, "marshal_load", iseq_marshal_load, 1); #endif /* disable this feature because there is no verifier. */ /* rb_define_singleton_method(rb_cISeq, "load", iseq_s_load, -1); */ (void)iseq_s_load; rb_define_singleton_method(rb_cISeq, "compile", iseq_s_compile, -1); rb_define_singleton_method(rb_cISeq, "new", iseq_s_compile, -1); rb_define_singleton_method(rb_cISeq, "compile_file", iseq_s_compile_file, -1); rb_define_singleton_method(rb_cISeq, "compile_option", iseq_s_compile_option_get, 0); rb_define_singleton_method(rb_cISeq, "compile_option=", iseq_s_compile_option_set, 1); rb_define_singleton_method(rb_cISeq, "disasm", iseq_s_disasm, 1); rb_define_singleton_method(rb_cISeq, "disassemble", iseq_s_disasm, 1); rb_define_singleton_method(rb_cISeq, "of", iseq_s_of, 1); }
27.543263
118
0.650251
eb82f9ff996824c82e21d4c29e062f0610563062
1,736
h
C
contrib/src/ai/pathFind.h
sean5470/panda3d
ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d
[ "PHP-3.0", "PHP-3.01" ]
3
2020-01-02T08:43:36.000Z
2020-07-05T08:59:02.000Z
contrib/src/ai/pathFind.h
sean5470/panda3d
ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
contrib/src/ai/pathFind.h
sean5470/panda3d
ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d
[ "PHP-3.0", "PHP-3.01" ]
1
2020-03-11T17:38:45.000Z
2020-03-11T17:38:45.000Z
/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file pathFind.h * @author Deepak, John, Navin * @date 2009-10-12 */ #ifndef _PATHFIND_H #define _PATHFIND_H #include "aiGlobals.h" #include "aiCharacter.h" #include "aiPathFinder.h" #include "boundingSphere.h" class AICharacter; /** * This class contains all the members and functions that are required to form * an interface between the AIBehaviors class and the PathFinder class. An * object (pointer) of this class is provided in the AIBehaviors class. It is * only via this object that the user can activate pathfinding. */ class EXPCL_PANDAAI PathFind { public: AICharacter *_ai_char; PathFinder *_path_finder_obj; NavMesh _nav_mesh; NavMesh _stage_mesh; int _grid_size; NodePath _path_find_target; LVecBase3 _prev_position; PT(GeomNode) _parent; LineSegs *_pen; vector<int> _previous_obstacles; bool _dynamic_avoid; vector<NodePath> _dynamic_obstacle; PathFind(AICharacter *ai_ch); ~PathFind(); void clear_path(); void trace_path(Node* src); void create_nav_mesh(const char* navmesh_filename); void assign_neighbor_nodes(const char* navmesh_filename); void do_dynamic_avoid(); void clear_previous_obstacles(); void set_path_find(const char* navmesh_filename); void path_find(LVecBase3 pos, string type = "normal"); void path_find(NodePath target, string type = "normal"); void add_obstacle_to_mesh(NodePath obstacle); void dynamic_avoid(NodePath obstacle); }; #endif
26.30303
78
0.751728
6fa7aacd40c0124a38f2155cbbcb5ead38c70060
273
h
C
DrakHorseWork/DrakHorseWork/Classes/Views/JKSportCPSButton.h
weizz123/WZSpotrs
8d39c7dfc7bf0d45e8c2206bc3cf482a6ab39e1a
[ "MIT" ]
null
null
null
DrakHorseWork/DrakHorseWork/Classes/Views/JKSportCPSButton.h
weizz123/WZSpotrs
8d39c7dfc7bf0d45e8c2206bc3cf482a6ab39e1a
[ "MIT" ]
null
null
null
DrakHorseWork/DrakHorseWork/Classes/Views/JKSportCPSButton.h
weizz123/WZSpotrs
8d39c7dfc7bf0d45e8c2206bc3cf482a6ab39e1a
[ "MIT" ]
null
null
null
// // JKSportCPSButton.h // DrakHorseWork // // Created by Jokin on 2017/4/24. // Copyright © 2017年 Jokin. All rights reserved. // #import <UIKit/UIKit.h> @interface JKSportCPSButton : UIButton @property (nonatomic, assign) IBInspectable BOOL isTrackBtn; @end
13
60
0.703297
172d66f5e7fb42e025db3bd89c86d6f51b9aa4bd
1,026
c
C
srcs/libft/ft_lstlast.c
hballaba/my-version-printf
ae6013ca0fd2e8ab296d2650ba3493cd9022b804
[ "Unlicense" ]
null
null
null
srcs/libft/ft_lstlast.c
hballaba/my-version-printf
ae6013ca0fd2e8ab296d2650ba3493cd9022b804
[ "Unlicense" ]
null
null
null
srcs/libft/ft_lstlast.c
hballaba/my-version-printf
ae6013ca0fd2e8ab296d2650ba3493cd9022b804
[ "Unlicense" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_lstlast.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hballaba <hballaba@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/05/23 17:39:21 by hballaba #+# #+# */ /* Updated: 2020/05/23 17:39:25 by hballaba ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" t_list *ft_lstlast(t_list *lst) { if (!lst) return (0); while (lst->next) lst = lst->next; return (lst); }
44.608696
80
0.180312
c4b048eee4692746a8542bf0ca05a01c88360231
1,249
h
C
EventTracing/event_tracing/event_trace_session.h
killvxk/event-tracing-for-windows
d75551104bd8a97f2b89d0d7683a087e2468e77d
[ "MIT" ]
34
2017-03-15T21:59:30.000Z
2022-01-25T05:12:37.000Z
EventTracing/event_tracing/event_trace_session.h
kaimi-io/event-tracing-for-windows
d75551104bd8a97f2b89d0d7683a087e2468e77d
[ "MIT" ]
null
null
null
EventTracing/event_tracing/event_trace_session.h
kaimi-io/event-tracing-for-windows
d75551104bd8a97f2b89d0d7683a087e2468e77d
[ "MIT" ]
8
2017-09-14T13:39:34.000Z
2021-03-24T03:57:35.000Z
#pragma once #include <cstdint> #include <string> #include <utility> #include <Windows.h> #include <Evntrace.h> #include "event_tracing/guid_helpers.h" namespace event_tracing { class event_trace_session { public: enum class trace_level : std::uint8_t { none = TRACE_LEVEL_NONE, critical = TRACE_LEVEL_CRITICAL, fatal = TRACE_LEVEL_FATAL, error = TRACE_LEVEL_ERROR, warning = TRACE_LEVEL_WARNING, information = TRACE_LEVEL_INFORMATION, verbose = TRACE_LEVEL_VERBOSE }; public: template<typename String> explicit event_trace_session(String&& session_name) : session_name_(std::forward<String>(session_name)) { create_or_replace_trace_session(); } event_trace_session(const event_trace_session&) = delete; event_trace_session& operator=(const event_trace_session&) = delete; ~event_trace_session(); void close_trace_session(); void enable_trace(const ms_guid& provider_guid, trace_level level); void enable_trace(const ms_guid& provider_guid, trace_level level, std::uint64_t match_any_keywords); const std::wstring& get_name() const noexcept { return session_name_; } private: void create_or_replace_trace_session(); TRACEHANDLE handle_ = 0; std::wstring session_name_; }; } //namespace event_tracing
22.303571
102
0.778223
5b4f92a5a976974e7f27f0e2e3909d3814794ac3
22,307
h
C
include/vke/Core/Utils/TCDynamicArray.h
przemyslaw-szymanski/vke
1d8fb139e0e995e330db6b8873dfc49463ec312c
[ "MIT" ]
1
2018-01-06T04:44:36.000Z
2018-01-06T04:44:36.000Z
include/vke/Core/Utils/TCDynamicArray.h
przemyslaw-szymanski/vke
1d8fb139e0e995e330db6b8873dfc49463ec312c
[ "MIT" ]
null
null
null
include/vke/Core/Utils/TCDynamicArray.h
przemyslaw-szymanski/vke
1d8fb139e0e995e330db6b8873dfc49463ec312c
[ "MIT" ]
null
null
null
#pragma once #include "TCContainerBase.h" namespace VKE { namespace Utils { #define TC_DYNAMIC_ARRAY_TEMPLATE \ template \ < \ typename DataType, \ uint32_t DEFAULT_ELEMENT_COUNT, \ class AllocatorType, \ class Policy, \ class Utils \ > #define TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS \ DataType, DEFAULT_ELEMENT_COUNT, AllocatorType, Policy, Utils #define TC_DYNAMIC_ARRAY_TEMPLATE2 \ template \ < \ typename DataType2, \ uint32_t DEFAULT_ELEMENT_COUNT2, \ class AllocatorType2, \ class Policy2, \ class Utils2 \ > #define TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS2 \ DataType2, DEFAULT_ELEMENT_COUNT2, AllocatorType2, Policy2, Utils2 struct DynamicArrayDefaultPolicy { // On Resize struct Resize { static uint32_t Calc(uint32_t current) { return current; } }; // On Reserve struct Reserve { static uint32_t Calc(uint32_t current) { return current; } }; // On PushBack struct PushBack { static uint32_t Calc(uint32_t current) { return current * 2; } }; // On Remove struct Remove { }; }; struct DynamicArrayDefaultUtils : public ArrayContainerDefaultUtils { }; template < typename T, uint32_t DEFAULT_ELEMENT_COUNT = 32, class AllocatorType = Memory::CHeapAllocator, class Policy = DynamicArrayDefaultPolicy, class Utils = DynamicArrayDefaultUtils > class TCDynamicArray : public TCArrayContainer< T, AllocatorType, Policy, Utils > { using Base = TCArrayContainer< T, AllocatorType, Policy, Utils >; public: static_assert( DEFAULT_ELEMENT_COUNT > 0, "DEFAULT_ELEMENT_COUNT must be greater than 0." ); using DataType = T; using DataTypePtr = T*; using DataTypeRef = T&; using SizeType = uint32_t; using CountType = uint32_t; using AllocatorPtr = Memory::IAllocator*; using Iterator = TCArrayIterator< DataType >; using ConstIterator = TCArrayIterator< const DataType >; template<uint32_t COUNT, class AllocatorType, class Policy> using TCOtherSizeArray = TCDynamicArray< T, COUNT, AllocatorType, Policy >; public: TCDynamicArray() { this->m_capacity = sizeof( m_aData ); this->m_pCurrPtr = m_aData; this->m_resizeElementCount = DEFAULT_ELEMENT_COUNT; } TCDynamicArray(std::initializer_list<DataType> List); explicit TCDynamicArray(const uint32_t& count) : TCDynamicArray() { const auto res = Resize( count ); VKE_ASSERT( res, "" ); } explicit TCDynamicArray(const uint32_t& count, const DataType& DefaultValue) : TCDynamicArray() { const auto res = Resize( count, DefaultValue ); VKE_ASSERT( res, "" ); } //TCDynamicArray(uint32_t count, VisitCallback&& Callback) : // //TCDynamicArray(), // TCArrayContainer(count, Callback) //{ // auto res = Resize( count, Callback ); // VKE_ASSERT( res, "" ); //} TCDynamicArray(const TCDynamicArray& Other); TCDynamicArray(TCDynamicArray&& Other); TC_DYNAMIC_ARRAY_TEMPLATE2 TCDynamicArray(const TCDynamicArray< TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS2 >& Other); TC_DYNAMIC_ARRAY_TEMPLATE2 TCDynamicArray(TCDynamicArray< TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS2 >&& Other); virtual ~TCDynamicArray() { Destroy(); } /*SizeType GetCapacity() const { return m_capacity; } CountType GetCount() const { return m_count; } SizeType CalcSize() const { return m_count * sizeof(DataType); }*/ SizeType GetMaxCount() const { return m_resizeElementCount; } template<EVENT_REPORT_TYPE = EventReportTypes::NONE> uint32_t PushBack(const DataType& el); template<EVENT_REPORT_TYPE = EventReportTypes::NONE> uint32_t PushBack(DataType&& el); bool PopBack(DataTypePtr pOut); template<bool DestructObject = true> bool PopBack(); DataType PopBackFast(); // do not check for emptyness bool Resize(); bool Resize(CountType newElemCount); bool Resize(CountType newElemCount, const DataType& DefaultData); bool Reserve(CountType elemCount); bool grow(CountType newElemCount, bool Resize = false); bool shrink(CountType newElemCount, bool Resize = false); void Remove(CountType elementIdx); void RemoveFast(CountType elemtnIdx); template<bool DestroyElements = true> void _Clear(); void Clear() { _Clear<false>(); } void ClearFull() { _Clear<true>(); } void Destroy(); //bool Copy(const TCDynamicArray& Other); void Move(TCDynamicArray* pOut); bool Append(const TCDynamicArray& Other) { return Append(0, Other.GetCount(), Other); } bool Append(CountType begin, CountType end, const TCDynamicArray& Other); bool Append(CountType begin, CountType end, const DataType* pData); bool Append(CountType count, const DataType* pData); bool IsInConstArrayRange(SizeType size) const { return size <= sizeof(m_aData); } Iterator begin() { return Iterator(this->m_pCurrPtr, this->m_pCurrPtr + this->m_count); } Iterator end() { return Iterator(this->m_pCurrPtr + this->m_count, this->m_pCurrPtr + this->m_count); } ConstIterator begin() const { return ConstIterator(this->m_pCurrPtr, this->m_pCurrPtr + this->m_count); } ConstIterator end() const { return ConstIterator(this->m_pCurrPtr + this->m_count, this->m_pCurrPtr + this->m_count); } TCDynamicArray& operator=(const TCDynamicArray& Other) { Copy( Other ); return *this; } TCDynamicArray& operator=(TCDynamicArray&& Other) { Move( &Other ); return *this; } protected: template<EVENT_REPORT_TYPE> void _ReportPushBack(const uint32_t oldCount, const uint32_t newCount); void _SetCurrPtr(); protected: DataType m_aData[ DEFAULT_ELEMENT_COUNT ]; CountType m_resizeElementCount = DEFAULT_ELEMENT_COUNT; }; TC_DYNAMIC_ARRAY_TEMPLATE TCDynamicArray<TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS>::TCDynamicArray(const TCDynamicArray& Other) : TCDynamicArray() { const auto res = Copy( Other ); VKE_ASSERT( res, "" ); } TC_DYNAMIC_ARRAY_TEMPLATE TCDynamicArray<TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS>::TCDynamicArray(TCDynamicArray&& Other) : TCDynamicArray() { Move( &Other ); } TC_DYNAMIC_ARRAY_TEMPLATE TC_DYNAMIC_ARRAY_TEMPLATE2 TCDynamicArray<TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS>::TCDynamicArray( const TCDynamicArray< TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS2 >& Other) : TCDynamicArray() { const auto res = Copy( Other ); VKE_ASSERT(res, "" ); } TC_DYNAMIC_ARRAY_TEMPLATE TC_DYNAMIC_ARRAY_TEMPLATE2 TCDynamicArray<TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS>::TCDynamicArray( TCDynamicArray< TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS2 >&& Other) : TCDynamicArray() { Move( &Other ); } TC_DYNAMIC_ARRAY_TEMPLATE TCDynamicArray<TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS>::TCDynamicArray(std::initializer_list<DataType> List) : TCDynamicArray() { const auto count = static_cast<CountType>(List.size()); if (count <= m_resizeElementCount) { for (auto& El : List) { m_aData[m_count++] = El; } } else { const auto newMaxCount = Policy::Reserve::Calc(count); Reserve( newMaxCount ); for (auto& El : List) { m_pData[m_count++] = El; } } } TC_DYNAMIC_ARRAY_TEMPLATE void TCDynamicArray<TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS>::Destroy() { TCArrayContainer::Destroy(); if( this->m_resizeElementCount ) { this->_DestroyElements( m_aData, DEFAULT_ELEMENT_COUNT ); } this->m_pCurrPtr = m_aData; m_capacity = sizeof( m_aData ); m_resizeElementCount = 0; } TC_DYNAMIC_ARRAY_TEMPLATE template<bool DestroyElements> void TCDynamicArray<TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS>::_Clear() { VKE_ASSERT(this->m_pCurrPtr, "" ); if( DestroyElements ) { this->_DestroyElements(this->m_pCurrPtr, this->m_count); } m_count = 0; } TC_DYNAMIC_ARRAY_TEMPLATE void TCDynamicArray<TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS>::Move(TCDynamicArray* pOut) { VKE_ASSERT( this->m_pCurrPtr, "" ); VKE_ASSERT( pOut, "" ); if( this == pOut ) { return; } const SizeType srcCapacity = pOut->GetCount() * sizeof( DataType ); if( IsInConstArrayRange( srcCapacity ) ) { // Copy for( CountType i = 0; i < pOut->GetCount(); ++i ) { this->m_aData[ i ] = std::move( pOut->m_pCurrPtr[ i ] ); } this->m_pCurrPtr = m_aData; } else { m_pData = pOut->m_pData; this->m_pCurrPtr = m_pData; } m_capacity = pOut->GetCapacity(); m_count = pOut->GetCount(); m_resizeElementCount = pOut->GetMaxCount(); pOut->m_pData = nullptr; pOut->m_pCurrPtr = pOut->m_aData; pOut->m_count = 0; pOut->m_capacity = sizeof( pOut->m_aData ); } TC_DYNAMIC_ARRAY_TEMPLATE bool TCDynamicArray<TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS>::Reserve(CountType elemCount) { VKE_ASSERT( this->m_pCurrPtr, "" ); if( TCArrayContainer::Reserve( elemCount ) ) { if( this->m_pData ) { this->m_pCurrPtr = this->m_pData; } else { this->m_pCurrPtr = m_aData; } return true; } return false; } TC_DYNAMIC_ARRAY_TEMPLATE bool TCDynamicArray<TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS>::Resize(CountType newElemCount) { VKE_ASSERT(this->m_pCurrPtr, "" ); bool res = true; if( m_resizeElementCount < newElemCount ) { res = TCArrayContainer::Resize( newElemCount ); if( res ) { m_resizeElementCount = newElemCount; this->m_pCurrPtr = this->m_pData; /*if( this->m_pCurrPtr != this->m_aData ) { Memory::Zero( m_aData, DEFAULT_ELEMENT_COUNT ); }*/ } } else { this->m_count = newElemCount; } return res; } TC_DYNAMIC_ARRAY_TEMPLATE bool TCDynamicArray<TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS>::Resize( CountType newElemCount, const DataType& Default) { if (Resize(newElemCount)) { for (uint32_t i = m_count; i-- > 0;) { this->m_pCurrPtr[i] = Default; } return true; } return false; } TC_DYNAMIC_ARRAY_TEMPLATE bool TCDynamicArray<TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS>::Resize() { return Resize(DEFAULT_ELEMENT_COUNT); } TC_DYNAMIC_ARRAY_TEMPLATE template<EVENT_REPORT_TYPE EventReportType> void TCDynamicArray<TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS>::_ReportPushBack(const uint32_t oldCount, const uint32_t newCount) { if( EventReportType != EventReportTypes::NONE ) { char buff[ 256 ]; vke_sprintf( buff, sizeof( buff ), "Resize: %d -> %d", oldCount, newCount ); if( EventReportType == EventReportTypes::ASSERT_ON_ALLOC ) { VKE_ASSERT( false, buff ); } } } TC_DYNAMIC_ARRAY_TEMPLATE template<EVENT_REPORT_TYPE EventReportType> uint32_t TCDynamicArray<TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS>::PushBack(const DataType& El) { if( this->m_count < m_resizeElementCount ) { //this->m_pCurrPtr[m_count++] = El; auto& Element = this->m_pCurrPtr[ m_count++ ]; Element = El; } else { // Need Resize const auto lastCount = m_count; const auto count = Policy::PushBack::Calc( m_resizeElementCount ); if( Resize( count ) ) { _ReportPushBack< EventReportType >( lastCount, count ); m_resizeElementCount = m_count; this->m_count = lastCount; return PushBack( El ); } return INVALID_POSITION; } return this->m_count - 1; } TC_DYNAMIC_ARRAY_TEMPLATE template<EVENT_REPORT_TYPE EventReportType> uint32_t TCDynamicArray<TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS>::PushBack(DataType&& El) { if( this->m_count < m_resizeElementCount ) { //this->m_pCurrPtr[m_count++] = El; auto& Element = this->m_pCurrPtr[ m_count++ ]; Element = std::move( El ); } else { // Need Resize const auto lastCount = m_count; const auto count = Policy::PushBack::Calc( m_resizeElementCount ); if( Resize( count ) ) { _ReportPushBack< EventReportType >( lastCount, count ); m_resizeElementCount = m_count; m_count = lastCount; return PushBack( El ); } return INVALID_POSITION; } return m_count - 1; } TC_DYNAMIC_ARRAY_TEMPLATE bool TCDynamicArray<TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS>::PopBack(DataTypePtr pOut) { VKE_ASSERT(pOut, "" ); if( !this->IsEmpty() ) { *pOut = Back(); this->m_count--; return true; } return false; } TC_DYNAMIC_ARRAY_TEMPLATE template<bool DestructObject> bool TCDynamicArray<TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS>::PopBack() { if( !this->IsEmpty() ) { this->m_count--; return true; } return false; } TC_DYNAMIC_ARRAY_TEMPLATE DataType TCDynamicArray<TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS>::PopBackFast() { VKE_ASSERT( !IsEmpty(), "Container is empty." ); DataType ret = Back(); this->m_count--; return ret; } TC_DYNAMIC_ARRAY_TEMPLATE bool TCDynamicArray<TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS>::Append( CountType begin, CountType end, const TCDynamicArray& Other) { return Append(begin, end, Other.m_pCurrPtr); } TC_DYNAMIC_ARRAY_TEMPLATE bool TCDynamicArray<TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS>::Append( CountType count, const DataType* pData) { const auto currCount = GetCount(); return Append(0, count, pData); } TC_DYNAMIC_ARRAY_TEMPLATE bool TCDynamicArray<TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS>::Append(CountType begin, CountType end, const DataType* pData) { VKE_ASSERT(begin <= end, "" ); const auto count = end - begin; if( count ) { const auto lastCount = this->GetCount(); if( lastCount + count > GetMaxCount() ) { const auto newCount = Policy::PushBack::Calc( GetMaxCount() + count ); if( !Resize( newCount ) ) { return false; } this->m_count = lastCount; } const auto dstSize = this->m_capacity - this->m_count * sizeof(DataType); const auto bytesToCopy = count * sizeof(DataType); DataTypePtr pCurrPtr = this->m_pCurrPtr + this->m_count; Memory::Copy(pCurrPtr, dstSize, pData + begin, bytesToCopy); this->m_count += count; return true; } return true; } TC_DYNAMIC_ARRAY_TEMPLATE void TCDynamicArray<TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS>::Remove(CountType elementIdx) { const auto dstSize = m_capacity - sizeof(DataType); const auto sizeToCopy = (m_resizeElementCount - 1) * sizeof(DataType); Memory::Copy(this->m_pCurrPtr + elementIdx, dstSize, this->m_pCurrPtr + elementIdx + 1, sizeToCopy); this->m_count--; } TC_DYNAMIC_ARRAY_TEMPLATE void TCDynamicArray<TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS>::RemoveFast(CountType elementIdx) { this->m_pCurrPtr[elementIdx] = Back(); m_count--; } TC_DYNAMIC_ARRAY_TEMPLATE void TCDynamicArray<TC_DYNAMIC_ARRAY_TEMPLATE_PARAMS>::_SetCurrPtr() { if (this->m_pData != nullptr) { this->m_pCurrPtr = this->m_pData; } else { this->m_pCurrPtr = this->m_aData; } } template < typename T, typename HandleType = uint32_t, uint32_t DEFAULT_ELEMENT_COUNT = 32, class AllocatorType = Memory::CHeapAllocator, class Policy = DynamicArrayDefaultPolicy > struct TSFreePool { static_assert( std::is_unsigned<HandleType>::value, "HandleType must be of unsigned type." ); using Array = Utils::TCDynamicArray< T, DEFAULT_ELEMENT_COUNT, AllocatorType, Policy >; using HandleArray = Utils::TCDynamicArray< HandleType, DEFAULT_ELEMENT_COUNT >; Array vPool; HandleArray vFreeElements; void Clear() { vPool.Clear(); vFreeElements.Clear(); } void FullClear() { vPool.ClearFull(); vFreeElements.ClearFull(); } HandleType Add( const T& element ) { HandleType ret; if( GetFreeHandle( &ret ) ) { vPool[ret] = ( element ); } else { ret = static_cast< HandleType >( vPool.PushBack( ( element ) ) ); } return ret; } HandleType Add( T&& element ) { HandleType ret; if( GetFreeHandle( &ret ) ) { vPool[ ret ] = std::move( element ); } else { ret = static_cast< HandleType >( vPool.PushBack( std::move( element ) ) ); } return ret; } void Free( const HandleType& handle ) { vFreeElements.PushBack( handle ); } bool GetFreeHandle(HandleType* phOut) { return vFreeElements.PopBack( phOut ); } uint32_t GetHandle() { uint32_t ret; if( !GetFreeHandle( &ret ) ) { ret = Add( {} ); } return ret; } T& operator[](const HandleType& handle) { return vPool[handle]; } const T& operator[]( const HandleType& handle ) const { return vPool[handle]; } }; } // Utils } // VKE
34.265745
135
0.505043
b204f09197a605cb3cb7c30e7b580d333a69c44e
31,945
h
C
Resources/doom3d.h
christymarc/raycasting-simulation
ed9b92143d3eb1c5a25900419ead517f93f8c315
[ "MIT" ]
3
2020-10-16T18:59:18.000Z
2021-03-23T00:46:09.000Z
Resources/doom3d.h
christymarc/raycasting-simulation
ed9b92143d3eb1c5a25900419ead517f93f8c315
[ "MIT" ]
3
2020-12-09T21:34:34.000Z
2021-06-04T05:17:51.000Z
Resources/doom3d.h
christymarc/raycasting-simulation
ed9b92143d3eb1c5a25900419ead517f93f8c315
[ "MIT" ]
5
2020-12-09T00:49:23.000Z
2021-06-01T07:40:41.000Z
#ifndef _DOOM3D_H_ #define _DOOM3D_H_ // TODO: // 1. check for TODO // 2. remove casts? might not need them for non-pointer types // 3. switch from array to vector or Array // Doom 3D engine ver: 1.000 // Originally by: Spektre on stackoverflow // https://stackoverflow.com/questions/47239797/ray-casting-with-different-height-size/47251071#47251071 // // Edited by: Anthony Clark #include <cmath> #include <string> using std::string; #include <fstream> using std::ifstream; using std::ofstream; #include <iostream> using std::cerr; using uint = unsigned int; constexpr long double deg2rad(long double deg) { return deg * 3.141592 / 180; } constexpr long double operator"" _deg(long double deg) { return deg2rad(deg); } const uint _Doom3D_cell_size = 10; // 2D map cell size const uint _Doom3D_wall_size = 100; // full height of wall in map #define _Doom3D_filter_txr class Doom3D { public: uint mxs, mys, **pmap; // 2D map // txr + height<<16 uint sxs, sys, **pscr; // pseudo 3D screen // Graphics::TBitmap *scr; uint8_t *canvas; uint txs, tys, **ptxr, tn; // 2D textures // Graphics::TBitmap *txr, *txr2; // textures, texture mipmaps resolution: /2 and /4 uint8_t *texture; double plrx, plry, plrz, plra; // player position [x,y,z,angle] double view_ang; // [rad] view angle double focus; // [cells] view focal length struct _ray { double x, y, l; // hit or end of map position uint hit; // map cell of hit or 0xFFFFFFFF char typ; // H/V _ray(){}; _ray(_ray &a) { *this = a; } ~_ray(){}; _ray *operator=(const _ray *a) { *this = *a; return this; } //_ray* operator = (const _ray &a) { ..copy... return this; } }; _ray *ray; // ray[sxs] // keytab keys; uint txr_sel; uint cell_h; Doom3D(); Doom3D(Doom3D &a) { *this = a; } ~Doom3D(); Doom3D *operator=(const Doom3D *a) { *this = *a; return this; } //Doom3D* operator = (const Doom3D &a) { ..copy... return this; } void map_resize(uint xs, uint ys); // change map resolution void map_height(uint height); // set height for whole map to convert maps from Wolfenstein3D demo void map_clear(); // clear whole map void map_save(string name); void map_load(string name); void scr_resize(uint xs, uint ys); void txr_load(string name); void draw(); void update(double dt); // void mouse(double x, double y, TShiftState sh) // { // x = floor(x / _Doom3D_cell_size); // if (x >= mxs) // x = mxs - 1; // if (x < 0) // x = 0; // y = floor(y / _Doom3D_cell_size); // if (y >= mys) // y = mys - 1; // if (y < 0) // y = 0; // uint xx = x, yy = y; // keys.setm(x, y, sh); // if (keys.Shift.Contains(ssLeft)) // pmap[yy][xx] = (txr_sel) | (cell_h << 16); // if (keys.Shift.Contains(ssRight)) // pmap[yy][xx] = 0xFFFFFFFF; // keys.rfsmouse(); // } // void wheel(int delta, TShiftState sh) // { // if (sh.Contains(ssShift)) // { // if (delta < 0) // { // cell_h -= 10; // if (cell_h < 10) // cell_h = 10; // } // if (delta > 0) // { // cell_h += 10; // if (cell_h > _Doom3D_wall_size) // cell_h = _Doom3D_wall_size; // } // } // else // { // if (delta < 0) // { // txr_sel--; // if (txr_sel == 0xFFFFFFFF) // txr_sel = tn - 1; // } // if (delta > 0) // { // txr_sel++; // if (txr_sel == tn) // txr_sel = 0; // } // } // } }; //--------------------------------------------------------------------------- Doom3D::Doom3D() { mxs = 0; mys = 0; pmap = nullptr; sxs = 0; sys = 0; // scr = new Graphics::TBitmap; canvas = nullptr; pscr = nullptr; ray = nullptr; txs = 0; tys = 0; // txr = new Graphics::TBitmap; texture = nullptr; ptxr = nullptr; tn = 0; // txr2 = new Graphics::TBitmap; plrx = 0.0; plry = 0.0; plrz = 0.0; plra = 0.0; view_ang = 60.0_deg; focus = 0.25; txr_sel = 0; cell_h = _Doom3D_wall_size; txr_load("textures/textures128x128.ppm"); map_resize(16, 16); map_load("Doom3D_map.dat"); } //--------------------------------------------------------------------------- Doom3D::~Doom3D() { uint y; map_save("Doom3D_map.dat"); if (pmap) { for (y = 0; y < mys; y++) delete[] pmap[y]; delete[] pmap; pmap = nullptr; } if (ray) delete[] ray; ray = nullptr; if (pscr) { delete[] pscr; pscr = nullptr; } // if (scr) // delete scr; // scr = nullptr; if (canvas) { delete[] canvas; } canvas = nullptr; if (ptxr) { delete[] ptxr; ptxr = nullptr; } // if (txr) // delete txr; // txr = nullptr; if (texture) { delete[] texture; } texture = nullptr; // if (txr2) // delete txr2; // txr2 = nullptr; } //--------------------------------------------------------------------------- void Doom3D::map_resize(uint xs, uint ys) { uint y; if (pmap) { for (y = 0; y < mys; y++) delete[] pmap[y]; delete[] pmap; pmap = nullptr; } mys = ys; mxs = xs; pmap = new uint *[mys]; for (y = 0; y < mys; y++) pmap[y] = new uint[mxs]; map_clear(); plrx = (mxs - 1) * 0.5; plry = (mys - 1) * 0.5; plrz = 0.0; plra = 0.0_deg; } //--------------------------------------------------------------------------- void Doom3D::map_height(uint h) { uint x, y, c; for (y = 0; y < mys; y++) for (x = 0; x < mxs; x++) { c = pmap[y][x]; c &= 0xFFFF; c |= h << 16; pmap[y][x] = c; } } //--------------------------------------------------------------------------- void Doom3D::map_clear() { uint x, y, c; for (y = 0; y < mys; y++) for (x = 0; x < mxs; x++) { c = 0xFFFFFFFF; if ((x == 0) || (x == mxs - 1)) c = 0; if ((y == 0) || (y == mys - 1)) c = 0; pmap[y][x] = c; } } //--------------------------------------------------------------------------- void Doom3D::map_save(string name) { // int hnd = FileCreate(name); // if (hnd < 0) // return; ofstream map_outfile(name, std::ios::binary); if (!map_outfile.is_open()) { cerr << "Could not open file: " << name << "\n"; return; } uint y; y = ' PAM'; // FileWrite(hnd, &y, 4); // id map_outfile.write(reinterpret_cast<char *>(&y), sizeof(y)); // FileWrite(hnd, &mxs, 4); // x resolution map_outfile.write(reinterpret_cast<char *>(&mxs), sizeof(mxs)); // FileWrite(hnd, &mys, 4); // y resolution map_outfile.write(reinterpret_cast<char *>(&mys), sizeof(mys)); // for (y = 0; y < mys; y++) // map // FileWrite(hnd, pmap[y], mxs << 2); for (y = 0; y < mys; y++) { map_outfile.write(reinterpret_cast<char *>(pmap[y]), sizeof(pmap[y][0]) * mxs); } y = ' RLP'; // FileWrite(hnd, &y, 4); // id map_outfile.write(reinterpret_cast<char *>(&y), sizeof(y)); // FileWrite(hnd, &plrx, 8); map_outfile.write(reinterpret_cast<char *>(&plrx), sizeof(plrx)); // FileWrite(hnd, &plry, 8); map_outfile.write(reinterpret_cast<char *>(&plry), sizeof(plry)); // FileWrite(hnd, &plrz, 8); map_outfile.write(reinterpret_cast<char *>(&plrz), sizeof(plrz)); // FileWrite(hnd, &plra, 8); map_outfile.write(reinterpret_cast<char *>(&plra), sizeof(plra)); // FileClose(hnd); } //--------------------------------------------------------------------------- void Doom3D::map_load(string name) { // int hnd = FileOpen(name, fmOpenRead); // if (hnd < 0) // return; ifstream map_infile(name, std::ios::binary); if (!map_infile.is_open()) { cerr << "Could not open file: " << name << "\n"; return; } uint x, y; y = ' PAM'; // FileRead(hnd, &x, 4); // id map_infile.read(reinterpret_cast<char *>(&x), sizeof(uint)); if (x == y) { // FileRead(hnd, &x, 4); // x resolution map_infile.read(reinterpret_cast<char *>(&x), sizeof(x)); // FileRead(hnd, &y, 4); // y resolution map_infile.read(reinterpret_cast<char *>(&y), sizeof(y)); map_resize(x, y); // for (y = 0; y < mys; y++) // map // FileRead(hnd, pmap[y], mxs << 2); for (y = 0; y < mys; y++) { map_infile.read(reinterpret_cast<char *>(pmap[y]), sizeof(pmap[y][0]) * mxs); } } y = ' RLP'; // FileRead(hnd, &x, 4); // id map_infile.read(reinterpret_cast<char *>(&x), sizeof(x)); if (x == y) { // FileRead(hnd, &plrx, 8); map_infile.read(reinterpret_cast<char *>(&plrx), sizeof(plrx)); // FileRead(hnd, &plry, 8); map_infile.read(reinterpret_cast<char *>(&plry), sizeof(plry)); // FileRead(hnd, &plrz, 8); map_infile.read(reinterpret_cast<char *>(&plrz), sizeof(plrz)); // FileRead(hnd, &plra, 8); map_infile.read(reinterpret_cast<char *>(&plra), sizeof(plra)); } // FileClose(hnd); } //--------------------------------------------------------------------------- void Doom3D::scr_resize(uint xs, uint ys) { // scr->HandleType = bmDIB; // scr->PixelFormat = pf32bit; // scr->SetSize(xs, ys); // sxs = scr->Width; // sys = scr->Height; // width BY height BY channels (RGB) canvas = new uint8_t[xs * ys * 3]; sxs = xs; sys = ys; delete[] pscr; pscr = new uint *[sys]; for (uint y = 0; y < sys; y++) { // pscr[y] = (uint *)scr->ScanLine[y]; // TODO: is this valid? pscr[y] = reinterpret_cast<uint *>(canvas + y * sxs); } if (ray) { delete[] ray; } ray = new _ray[sxs]; } //--------------------------------------------------------------------------- void Doom3D::txr_load(string name) { // string ext = ExtractFileExt(name).LowerCase(); // for (;;) // { // if (ext == ".bmp") // { // txr->LoadFromFile(name); // break; // } // if (ext == ".jpg") // { // TJPEGImage *jpg = new TJPEGImage; // if (jpg == nullptr) // return; // jpg->LoadFromFile(name); // txr->Assign(jpg); // delete jpg; // break; // } // return; // } // uint y = tys; // txr->HandleType = bmDIB; // txr->PixelFormat = pf32bit; // txs = txr->Width; // tys = txr->Height; // Open file, seek to the end, read the size, seek to beggining ifstream texture_file(name, std::ios::binary | std::ios::ate); std::streamsize texture_size = texture_file.tellg(); texture_file.seekg(0, std::ios::beg); // Read PPM header string header; int sizex, sizey, sizec; texture_file >> header >> sizex >> sizey >> sizec; std::cout << "Texture size : " << sizex * sizey * 3 << " (" << sizex << "x" << sizey << "x3)\n"; std::cout << "Expecting : " << 128 * 128 * 48 * 3 << "\n"; texture = new uint8_t[texture_size]; if (!texture_file.read(reinterpret_cast<char *>(texture), texture_size)) { cerr << "Could not read texture file.\n"; } txs = sizex; tys = sizey; // // mip map // txr2->SetSize(txs >> 1, (tys >> 1) + (tys >> 2)); // txr2->Canvas->StretchDraw(TRect(0, 0, txs >> 1, tys >> 1), txr); // txr2->Canvas->StretchDraw(TRect(0, tys >> 1, txs >> 2, (tys >> 1) + (tys >> 2)), txr); tn = txs / tys; txs = tys; delete[] ptxr; ptxr = new uint *[tys]; // for (y = 0; y < tys; y++) // ptxr[y] = (uint *)txr->ScanLine[y]; for (int y = 0; y < tys; y++) { ptxr[y] = reinterpret_cast<uint *>(texture + y * txs); } } //--------------------------------------------------------------------------- void Doom3D::draw() { // total time measurement // tbeg(); // double tperf0 = performance_tms; string tcls, tray, tmap, ttotal; double a, a0, da, dx, dy, l, mx, my; uint x, y, xs2, ys2, c, m; double xx0, yy0, dx0, dy0, ll0; uint c0, d0; double xx1, yy1, dx1, dy1, ll1; uint c1, d1; _ray *p; xs2 = sxs >> 1; ys2 = sys >> 1; // aspect ratio,view angle corrections a = 90.0_deg - view_ang; double wall = double(sxs) * (1.25 + (0.288 * a) + (2.04 * a * a)); // [px] // floor,ceilling/sky // tbeg(); for (y = 0; y < ys2; y++) for (x = 0; x < sxs; x++) pscr[y][x] = 0x000080FF; for (; y < sys; y++) for (x = 0; x < sxs; x++) pscr[y][x] = 0x00404040; // tend(); // tcls = tstr(1) + " cls"; // [cast rays] // tbeg(); // diffuse + ambient lighting uint ch = 155.0 + fabs(100.0 * sin(plra)); uint cv = 155.0 + fabs(100.0 * cos(plra)); a0 = plra - (0.5 * view_ang); // da = divide(view_ang, sxs - 1); // TODO: is this the correct way to handle divide by 0 here? da = (sxs - 1) == 0 ? 0 : view_ang / (sxs - 1); mx = mxs; my = mys; for (p = ray, a = a0, x = 0; x < sxs; x++, a += da, p++) { p->x = plrx; p->y = plry; p->hit = 0xFFFFFFFF; p->typ = ' '; p->l = 1.0e20; ll0 = ll1 = p->l; // grid V-line hits c0 = 0; dx0 = cos(a); if (dx0 < 0.0) { c0 = 1; xx0 = floor(plrx) - 0.001; dx0 = -1.0; } if (dx0 > 0.0) { c0 = 1; xx0 = ceil(plrx) + 0.001; dx0 = +1.0; } if (c0) { dy0 = tan(a); yy0 = plry + ((xx0 - plrx) * dy0); dy0 *= dx0; dx = xx0 - plrx; dy = yy0 - plry; ll0 = (dx * dx) + (dy * dy); } // grid H-line hits c1 = 0; dy1 = sin(a); if (dy1 < 0.0) { c1 = 1; yy1 = floor(plry) - 0.001; dy1 = -1.0; } if (dy1 > 0.0) { c1 = 1; yy1 = ceil(plry) + 0.001; dy1 = +1.0; } if (c1) { // dx1 = divide(1.0, tan(a)); // TODO: divide by 0? dx1 = tan(a) == 0 ? 0 : 1.0 / tan(a); xx1 = plrx + ((yy1 - plry) * dx1); dx1 *= dy1; dx = xx1 - plrx; dy = yy1 - plry; ll1 = (dx * dx) + (dy * dy); } int height0 = sys; // already rendered height [pixels] bool _hit, _back = false, _bck = true; if (!c0) ll0 = 1e20; if (!c1) ll1 = 1e20; for (; c0 || c1;) { _hit = false; // grid V-line hits if (c0) { if (xx0 < 0.0) { c0 = 0; ll0 = 1e20; } if (xx0 >= mx) { c0 = 0; ll0 = 1e20; } if (yy0 < 0.0) { c0 = 0; ll0 = 1e20; } if (yy0 >= my) { c0 = 0; ll0 = 1e20; } } if ((c0) && (ll0 < ll1)) { m = uint(xx0 - dx0); if ((m >= 0.0) && (m < mxs) && (!_bck)) { c = pmap[uint(yy0)][m]; if ((c & 0xFFFF) != 0xFFFF) { p->hit = c; p->typ = 'V'; p->l = ll0; p->x = xx0; p->y = yy0; _hit = true; _back = true; _bck = true; } } if (!_hit) { c = pmap[uint(yy0)][uint(xx0)]; if ((c & 0xFFFF) != 0xFFFF) { p->hit = c; p->typ = 'V'; p->l = ll0; p->x = xx0; p->y = yy0; _hit = true; _back = false; _bck = false; } xx0 += dx0; dx = xx0 - plrx; yy0 += dy0; dy = yy0 - plry; ll0 = (dx * dx) + (dy * dy); } } // grid H-line hits if (c1) { if (xx1 < 0.0) { c1 = 0; ll1 = 1e20; } if (xx1 >= mx) { c1 = 0; ll1 = 1e20; } if (yy1 < 0.0) { c1 = 0; ll1 = 1e20; } if (yy1 >= my) { c1 = 0; ll1 = 1e20; } } if ((c1) && (ll0 > ll1) && (!_hit)) { m = uint(yy1 - dy1); if ((m >= 0.0) && (m < mys) && (!_bck)) { c = pmap[m][uint(xx1)]; if ((c & 0xFFFF) != 0xFFFF) { p->hit = c; p->typ = 'H'; p->l = ll1; p->x = xx1; p->y = yy1; _hit = true; _back = true; _bck = true; } } if (!_hit) { c = pmap[uint(yy1)][uint(xx1)]; if ((c & 0xFFFF) != 0xFFFF) { p->hit = c; p->typ = 'H'; p->l = ll1; p->x = xx1; p->y = yy1; _hit = true; _back = false; _bck = false; } xx1 += dx1; dx = xx1 - plrx; yy1 += dy1; dy = yy1 - plry; ll1 = (dx * dx) + (dy * dy); } } // render scan line if (_hit) { union { uint dd; uint8_t db[4]; } cc; int tx, ty, sy, sy0, sy1, cnt, dsy, dty; p->l = sqrt(p->l) * cos(a - plra); // anti fish eye // m = divide(wall * focus, p->l); // projected wall half size // TODO: divide by 0 m = p->l == 0 ? 0 : (wall * focus) / p->l; c = 0; if (p->typ == 'H') { c = ch; tx = double(double(txs) * (p->x - floor(p->x))); } if (p->typ == 'V') { c = cv; tx = double(double(txs) * (p->y - floor(p->y))); } tx += txs * (p->hit & 0xFFFF); // prepare interpolation sy1 = ys2 + m; // sy0=ys2-m; // constant wall height sy0 = sy1 - (((m + m) * (p->hit >> 16)) / _Doom3D_wall_size); // variable wall height dty = tys - 1; dsy = sy1 - sy0 + 1; // skip sy>=sys if (sy1 >= sys) sy1 = sys - 1; // skip sy<0 for (cnt = dsy, sy = sy0, ty = 0; sy < 0; sy++) { cnt -= dty; while (cnt <= 0) { cnt += dsy; ty++; } } #ifdef _Doom3D_filter_txr uint r = 0, g = 0, b = 0, n = 0; #else cc.dd = ptxr[ty][tx]; cc.db[0] = uint((uint(cc.db[0]) * c) >> 8); cc.db[1] = uint((uint(cc.db[1]) * c) >> 8); cc.db[2] = uint((uint(cc.db[2]) * c) >> 8); #endif // continue sy>=0 y = height0; if (sy1 > height0) sy1 = height0; if (sy0 < height0) height0 = sy0; if (_back) { for (sy = sy0; sy <= y; sy++) { if ((sy > 0) && (sy < sys)) pscr[sy][x] = 0x0000FF00; } } else for (; sy <= sy1; sy++) { #ifdef _Doom3D_filter_txr if (!n) { cc.dd = ptxr[ty][tx]; b += uint(cc.db[0]); g += uint(cc.db[1]); r += uint(cc.db[2]); n += 256; } if ((sy > 0) && (sy < sys)) { cc.db[0] = uint(c * b / n); b = 0; cc.db[1] = uint(c * g / n); g = 0; cc.db[2] = uint(c * r / n); r = 0; n = 0; pscr[sy][x] = cc.dd; } cnt -= dty; while (cnt <= 0) { cnt += dsy; ty++; cc.dd = ptxr[ty][tx]; b += uint(cc.db[0]); g += uint(cc.db[1]); r += uint(cc.db[2]); n += 256; } #else if ((sy > 0) && (sy < sys)) pscr[sy][x] = cc.dd; cnt -= dty; while (cnt <= 0) { cnt += dsy; ty++; cc.dd = ptxr[ty][tx]; cc.db[0] = uint((uint(cc.db[0]) * c) >> 8); cc.db[1] = uint((uint(cc.db[1]) * c) >> 8); cc.db[2] = uint((uint(cc.db[2]) * c) >> 8); } #endif } if (height0 < 0) break; } } } // tend(); // tray = tstr(1) + " ray"; // [2D map] // tbeg(); m = _Doom3D_cell_size; mx = _Doom3D_cell_size; if ((sxs >= mxs * m) && (sys >= mys * m)) { for (y = 0; y < mys * m; y++) // pmap[][] for (x = 0; x < mxs * m; x++) { if ((pmap[y / m][x / m] & 0xFFFF) != 0xFFFF) c = 0x00808080; else c = 0x00000000; pscr[y][x] = c; } x = double(plrx * mx); // view rays y = double(plry * mx); // scr->Canvas->Pen->Color = 0x00005050; uint8_t r = 0, g = 0x50, b = 0x50; // scr->Canvas->Pen->Mode = pmMerge; for (c = 0; c < sxs; c++) { // scr->Canvas->MoveTo(x, y); // scr->Canvas->LineTo(uint(ray[c].x * mx), uint(ray[c].y * mx)); // Grid Walking: https://www.redblobgames.com/grids/line-drawing.html#stepping // int dx = uint(ray[c].x * mx) - x; // int dy = uint(ray[c].y * mx) - y; // int nx = dx > 0 ? dx : -dx; // int ny = dy > 0 ? dy : -dy; // int sign_x = dx > 0 ? 1 : -1; // int sign_y = dy > 0 ? 1 : -1; // int current_x = x; // int current_y = y; // for (int ix = 0, iy = 0; ix < nx || iy < ny;) // { // if ((0.5 + ix) / nx < (0.5 + iy) / ny) // { // // next step is horizontal // current_x += sign_x; // ix++; // } // else // { // // next step is vertical // current_y += sign_y; // iy++; // } // canvas[current_x + current_y * sxs + 0] = r; // canvas[current_x + current_y * sxs + 1] = g; // canvas[current_x + current_y * sxs + 2] = b; // std::cout << current_x << ", " << current_y << "\n"; // } } // scr->Canvas->Pen->Mode = pmCopy; c = focus * m; // player and view direction // scr->Canvas->Pen->Color = 0x000000FF; // scr->Canvas->Brush->Color = 0x000000FF; // scr->Canvas->MoveTo(x, y); // scr->Canvas->LineTo(uint(ray[xs2].x * mx), uint(ray[xs2].y * mx)); // scr->Canvas->Ellipse(x - c, y - c, x + c, y + c); // scr->Canvas->Pen->Color = 0x00202020; for (y = 0; y <= mys; y++) // map grid for (x = 0; x <= mxs; x++) { // scr->Canvas->MoveTo(0, y * m); // scr->Canvas->LineTo(mxs * m, y * m); // scr->Canvas->MoveTo(x * m, 0); // scr->Canvas->LineTo(x * m, mys * m); } // x = keys.mx * m; // selected cell // y = keys.my * m; // scr->Canvas->Pen->Color = 0x0020FFFF; // scr->Canvas->MoveTo(x, y); // scr->Canvas->LineTo(x + m, y); // scr->Canvas->LineTo(x + m, y + m); // scr->Canvas->LineTo(x, y + m); // scr->Canvas->LineTo(x, y); } // tend(); // tmap = tstr(1) + " map"; // [editor] if (txr_sel != 0xFFFFFFFF) { int x = sxs, y = 5, s0, s1, s2, i, j; s0 = txs >> 1; s1 = txs >> 2; s2 = (s0 * cell_h) / _Doom3D_wall_size; for (i = -3; i <= 3; i++) { j = txr_sel + i; while (j < 0) j += tn; while (j >= tn) j -= tn; if (i) { // scr->Canvas->CopyRect(TRect(x - s1, y + (s1 >> 1), x, s1 + (s1 >> 1)), txr2->Canvas, TRect(s1 * j, s0, s1 * j + s1, s0 + s1)); x -= s1 + 5; } else { // scr->Canvas->CopyRect(TRect(x - s0, y + s0 - s2, x, s0), txr2->Canvas, TRect(s0 * j, 0, s0 * j + s0, s2)); x -= s0 + 5; } } } // total time measurement // performance_tms = tperf0; // tend(); // ttotal = tstr(1) + " total"; x = m * mxs + m; c = 16; y = -c; // scr->Canvas->Font->Color = clYellow; // scr->Canvas->Brush->Style = bsClear; // scr->Canvas->TextOutA(x, y += c, string().sprintf("player: %.2lf x %.2lf x %.2lf", plrx, plry, plrz)); // scr->Canvas->TextOutA(x, y += c, string().sprintf(" mouse: %.2lf x %.2lf", keys.mx, keys.my)); // scr->Canvas->TextOutA(x, y += c, tray); // scr->Canvas->TextOutA(x, y += c, tcls); // scr->Canvas->TextOutA(x, y += c, tmap); // scr->Canvas->TextOutA(x, y += c, ttotal); // scr->Canvas->TextOutA(x, y += c, string().sprintf(" key: %d", keys.Key)); // aspect ratio test /* c=ys2*7/10; scr->Canvas->Rectangle(xs2-c,ys2-c,xs2+c,ys2+c); */ // cross // c = 4, m = 32; // scr->Canvas->Pen->Color = clRed; // scr->Canvas->MoveTo(xs2 - c, ys2 - m); // scr->Canvas->LineTo(xs2 - c, ys2 - c); // scr->Canvas->LineTo(xs2 - m, ys2 - c); // scr->Canvas->MoveTo(xs2 + c, ys2 - m); // scr->Canvas->LineTo(xs2 + c, ys2 - c); // scr->Canvas->LineTo(xs2 + m, ys2 - c); // scr->Canvas->MoveTo(xs2 - c, ys2 + m); // scr->Canvas->LineTo(xs2 - c, ys2 + c); // scr->Canvas->LineTo(xs2 - m, ys2 + c); // scr->Canvas->MoveTo(xs2 + c, ys2 + m); // scr->Canvas->LineTo(xs2 + c, ys2 + c); // scr->Canvas->LineTo(xs2 + m, ys2 + c); // scr->Canvas->Brush->Style = bsSolid; } //--------------------------------------------------------------------------- void Doom3D::update(double dt) { int move = 0; double da = 120.0_deg * dt; double dl = 5.0 * dt; double dx = 0.0, dy = 0.0, dz = 0.0; // if (keys.get(104)) // { // plra -= da; // if (plra < 0.0) // plra += pi2; // } // turn l/r // if (keys.get(105)) // { // plra += da; // if (plra >= pi2) // plra -= pi2; // } // if (keys.get(101)) // { // move = 1; // dx = +dl * cos(plra); // dy = +dl * sin(plra); // } // move f/b // if (keys.get(98)) // { // move = 1; // dx = -dl * cos(plra); // dy = -dl * sin(plra); // } // if (keys.get(102)) // { // move = 1; // dx = dl * cos(plra - 90_deg); // dy = dl * sin(plra - 90_deg); // } // strafe l/r // if (keys.get(99)) // { // move = 1; // dx = dl * cos(plra + 90_deg); // dy = dl * sin(plra + 90_deg); // } // if (keys.get(100)) // { // move = 1; // dz = +dl; // } // strafe u/d // if (keys.get(97)) // { // move = 1; // dz = -dl; // } if (move) // update/test plr position { double x, y, z, mx, my; x = plrx + dx; mx = mxs - focus; y = plry + dy; my = mys - focus; z = plrz + dz; if ((z >= 0.0) && (z <= _Doom3D_wall_size)) plrz = z; ; if (x < focus) x = focus; if (x > mx) x = mx; if (y < focus) y = focus; if (y > my) y = my; // dx *= divide(focus, dl); // TODO: divide by 0 dx *= dl == 0 ? 0 : focus / dl; // dy *= divide(focus, dl); // TODO: divide by 0 dy *= dl == 0 ? 0 : focus / dl; if ((pmap[uint(y + dy)][uint(x + dx)] & 0xFFFF) == 0xFFFF) { plrx = x; plry = y; } else if ((pmap[uint(y + dy)][uint(x)] & 0xFFFF) == 0xFFFF) plry = y; else if ((pmap[uint(y)][uint(x + dx)] & 0xFFFF) == 0xFFFF) plrx = x; } // keys.rfskey(); } //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #endif //--------------------------------------------------------------------------- //---------------------------------------------------------------------------
30.05174
145
0.363813
85753df3f142a721ac0a81f6e1ac77efb26c5bfa
3,785
h
C
src/nbl/video/CEGLCaller.h
deprilula28/Nabla
6b5de216221718191713dcf6de8ed6407182ddf0
[ "Apache-2.0" ]
null
null
null
src/nbl/video/CEGLCaller.h
deprilula28/Nabla
6b5de216221718191713dcf6de8ed6407182ddf0
[ "Apache-2.0" ]
null
null
null
src/nbl/video/CEGLCaller.h
deprilula28/Nabla
6b5de216221718191713dcf6de8ed6407182ddf0
[ "Apache-2.0" ]
null
null
null
#ifndef __NBL_C_EGL_CALLER_H_INCLUDED__ #define __NBL_C_EGL_CALLER_H_INCLUDED__ #include "EGL/egl.h" #include "nbl/system/DynamicFunctionCaller.h" #include "nbl/system/DefaultFuncPtrLoader.h" namespace nbl::video::egl { #define NBL_EGL_FUNC_LIST \ eglChooseConfig,\ eglCopyBuffers,\ eglCreateContext,\ eglCreatePbufferSurface,\ eglCreatePixmapSurface,\ eglCreateWindowSurface,\ eglDestroyContext,\ eglDestroySurface,\ eglGetConfigAttrib,\ eglGetConfigs,\ eglGetCurrentDisplay,\ eglGetCurrentSurface,\ eglGetDisplay,\ eglGetError,\ eglGetProcAddress,\ eglInitialize,\ eglMakeCurrent,\ eglQueryContext,\ eglQueryString,\ eglQuerySurface,\ eglSwapBuffers,\ eglTerminate,\ eglWaitGL,\ eglWaitNative,\ \ eglBindTexImage,\ eglReleaseTexImage,\ eglSurfaceAttrib,\ eglSwapInterval,\ \ eglBindAPI,\ eglQueryAPI,\ eglCreatePbufferFromClientBuffer,\ eglReleaseThread,\ eglWaitClient,\ \ eglGetCurrentContext,\ \ eglCreateSync,\ eglDestroySync,\ eglClientWaitSync,\ eglGetSyncAttrib,\ eglCreateImage,\ eglDestroyImage,\ eglGetPlatformDisplay,\ eglCreatePlatformWindowSurface,\ eglCreatePlatformPixmapSurface,\ eglWaitSync,\ eglGetPlatformDependentHandles #define NBL_IMPL_GET_FUNC_PTR(FUNC_NAME) reinterpret_cast<void*>(&::FUNC_NAME) class CEGLLoader : public system::FuncPtrLoader { system::DefaultFuncPtrLoader m_libEGL; public: CEGLLoader() : m_libEGL() {} CEGLLoader(const char* eglOptionalPath) : m_libEGL(eglOptionalPath) {} CEGLLoader(CEGLLoader&& other) : m_libEGL() { operator=(std::move(other)); } ~CEGLLoader() {} CEGLLoader& operator=(CEGLLoader&& other) { m_libEGL = std::move(other.m_libEGL); return *this; } inline bool isLibraryLoaded() override {return true;} void* loadFuncPtr(const char* funcname) override { if (m_libEGL.isLibraryLoaded()) return m_libEGL.loadFuncPtr(funcname); #define LOAD_DYNLIB_FUNCPTR(FUNC_NAME) if (strcmp(funcname, #FUNC_NAME )==0) \ return NBL_IMPL_GET_FUNC_PTR(FUNC_NAME); NBL_FOREACH(LOAD_DYNLIB_FUNCPTR,NBL_EGL_FUNC_LIST) #undef LOAD_DYNLIB_FUNCPTR return nullptr; } }; NBL_SYSTEM_DECLARE_DYNAMIC_FUNCTION_CALLER_CLASS(CEGLCaller,CEGLLoader,NBL_EGL_FUNC_LIST); /* class CEGLCaller final : public core::Uncopyable { public: #define NBL_IMPL_INIT_EGL_FUNCPTR(FUNC_NAME) ,p ## FUNC_NAME ( NBL_IMPL_GET_FUNC_PTR(FUNC_NAME) ) #define NBL_IMPL_INIT_EGL_FUNC_PTRS(...)\ NBL_FOREACH(NBL_IMPL_INIT_EGL_FUNCPTR,__VA_ARGS__) CEGLCaller() : core::Uncopyable() NBL_IMPL_INIT_EGL_FUNC_PTRS(NBL_EGL_FUNC_LIST) { } #undef NBL_IMPL_INIT_EGL_FUNC_PTRS #undef NBL_IMPL_INIT_EGL_FUNCPTR #undef NBL_IMPL_GET_FUNC_PTR CEGLCaller(CEGLCaller&& other) { operator=(std::move(other)); } CEGLCaller& operator=(CEGLCaller&& other) { #define NBL_IMPL_SWAP_EGL_FUNC_PTRS(...)\ NBL_FOREACH(NBL_SYSTEM_IMPL_SWAP_DYNLIB_FUNCPTR,__VA_ARGS__); NBL_IMPL_SWAP_EGL_FUNC_PTRS(NBL_EGL_FUNC_LIST); #undef NBL_IMPL_SWAP_EGL_FUNC_PTRS return *this; } #define NBL_IMPL_DECLARE_EGL_FUNC_PTRS(...)\ NBL_FOREACH(NBL_SYSTEM_DECLARE_DYNLIB_FUNCPTR,__VA_ARGS__); NBL_IMPL_DECLARE_EGL_FUNC_PTRS(NBL_EGL_FUNC_LIST) #undef NBL_IMPL_DECLARE_EGL_FUNC_PTRS }; */ #undef NBL_EGL_FUNC_LIST } #endif
27.035714
105
0.670013
12d473932e6948be7ad890a4056335cc338cd8ff
3,950
h
C
src/gamebase/include/gamebase/gameview/GameView.h
TheMrButcher/opengl_lessons
76ac96c45773a54a85d49c6994770b0c3496303f
[ "MIT" ]
1
2016-10-25T21:15:16.000Z
2016-10-25T21:15:16.000Z
src/gamebase/include/gamebase/gameview/GameView.h
TheMrButcher/gamebase
76ac96c45773a54a85d49c6994770b0c3496303f
[ "MIT" ]
375
2016-06-04T11:27:40.000Z
2019-04-14T17:11:09.000Z
src/gamebase/include/gamebase/gameview/GameView.h
TheMrButcher/gamebase
76ac96c45773a54a85d49c6994770b0c3496303f
[ "MIT" ]
null
null
null
/** * Copyright (c) 2018 Slavnejshev Filipp * This file is licensed under the terms of the MIT license. */ #pragma once #include <gamebase/impl/gameview/GameView.h> #include <gamebase/impl/pubhelp/Helpers.h> #include <gamebase/gameview/Layer.h> #include <gamebase/gameview/LayerVoidData.h> namespace gamebase { class GameView { public: Vec2 view() const; void setView(float x, float y); void setView(const Vec2& v); Box viewBox() const; Vec2 mousePos() const; template <typename DataType> void remove(const Layer<DataType>& layer); template <typename DataType> Layer<DataType> get(int id) const; template <typename DataType> Layer<DataType> get(const std::string& name) const; template <typename T> T child(const std::string& name) const; Layer<void> get(int id) const; Layer<void> get(const std::string& name) const; void remove(int id); void remove(const std::string& name); void clear(); bool isVisible() const; void setVisible(bool value); void show(); void hide(); bool isMouseOn() const; Box box() const; float width() const; float height() const; operator bool() const; template <typename DataType> Layer<DataType> load(const std::string& fileName); template <typename DataType> Layer<DataType> load(int id, const std::string& fileName); Layer<void> load(const std::string& fileName); Layer<void> load(int id, const std::string& fileName); GAMEBASE_DEFINE_PIMPL(GameView, GameView); }; /////////////// IMPLEMENTATION /////////////////// inline Vec2 GameView::view() const { return m_impl->viewCenter(); } inline void GameView::setView(float x, float y) { m_impl->setViewCenter(Vec2(x, y)); } inline void GameView::setView(const Vec2& v) { m_impl->setViewCenter(v); } inline Box GameView::viewBox() const { return m_impl->viewBox(); } inline Vec2 GameView::mousePos() const { return m_impl->mouseCoords(); } template <typename DataType> inline void GameView::remove(const Layer<DataType>& layer) { m_impl->removeObject(layer.getImpl().get()); } template <typename DataType> inline Layer<DataType> GameView::get(int id) const { return Layer<DataType>(impl::SmartPointer<impl::ILayer>(m_impl->getLayer<impl::ILayer>(id))); } template <typename DataType> inline Layer<DataType> GameView::get(const std::string& name) const { return Layer<DataType>(impl::SmartPointer<impl::ILayer>(m_impl->getLayer(name))); } template <typename T> inline T GameView::child(const std::string& name) const { return impl::findAndWrap<T>(m_impl.get(), name); } inline Layer<void> GameView::get(int id) const { return get<void>(id); } inline Layer<void> GameView::get(const std::string& name) const { return get<void>(name); } inline void GameView::remove(int id) { m_impl->removeLayer(id); } inline void GameView::remove(const std::string& name) { m_impl->removeLayer(name); } inline void GameView::clear() { m_impl->clear(); } inline Box GameView::box() const { return m_impl->viewBox(); } inline float GameView::width() const { return m_impl->box().width(); } inline float GameView::height() const { return m_impl->box().height(); } template <typename DataType> inline Layer<DataType> GameView::load(const std::string& fileName) { auto layerImpl = impl::deserializeLayer(fileName); m_impl->addLayer(layerImpl); return Layer<DataType>(impl::SmartPointer<impl::ILayer>(layerImpl.get())); } template <typename DataType> inline Layer<DataType> GameView::load(int id, const std::string& fileName) { auto layerImpl = impl::deserializeLayer(fileName); m_impl->insertLayer(id, layerImpl); return Layer<DataType>(impl::SmartPointer<impl::ILayer>(layerImpl.get())); } inline Layer<void> GameView::load(const std::string& fileName) { return load<void>(fileName); } inline Layer<void> GameView::load(int id, const std::string& fileName) { return load<void>(id, fileName); } GAMEBASE_DEFINE_DRAWABLE_METHODS(GameView); }
43.406593
182
0.710633
e96c1ecc5430e2eaac79389cafe18a4ce1042097
372
h
C
headers/tags.h
miles-canfield/Fifth
c80b02cbdc2822673b2e53edf428d664a5615fd3
[ "MIT" ]
1
2019-07-16T09:29:57.000Z
2019-07-16T09:29:57.000Z
headers/tags.h
miles-canfield/Fifth
c80b02cbdc2822673b2e53edf428d664a5615fd3
[ "MIT" ]
null
null
null
headers/tags.h
miles-canfield/Fifth
c80b02cbdc2822673b2e53edf428d664a5615fd3
[ "MIT" ]
null
null
null
#pragma once #define tag_eol 0x1 #define tag_bool 0x3 #define tag_char 0x5 #define tag_sym 0x7 #define tag_list 0x9 #define tag_arr 0xb #define tag_ptr 0xd #define tag_fun 0xf #define tag_u8 0x10 #define tag_i8 0x13 #define tag_u16 0x15 #define tag_i16 0x17 #define tag_u32 0x19 #define tag_i32 0x1b #define tag_u64 0x1d #define tag_i64 0x1f bool typep(u64 v);
16.173913
20
0.774194
eb1d8e0a7d2c5fcd392e6ac659da5133bce488f6
1,044
h
C
src/ufo/marine/insitutemperature/ObsInsituTemperature.interface.h
guoqing-noaa/ufo
68dab85486f5d79991956076ac6b962bc1a0c5bd
[ "Apache-2.0" ]
4
2020-12-04T08:26:06.000Z
2021-11-20T01:18:47.000Z
src/ufo/marine/insitutemperature/ObsInsituTemperature.interface.h
guoqing-noaa/ufo
68dab85486f5d79991956076ac6b962bc1a0c5bd
[ "Apache-2.0" ]
21
2020-10-30T08:57:16.000Z
2021-05-17T15:11:20.000Z
src/ufo/marine/insitutemperature/ObsInsituTemperature.interface.h
guoqing-noaa/ufo
68dab85486f5d79991956076ac6b962bc1a0c5bd
[ "Apache-2.0" ]
31
2021-06-24T18:07:53.000Z
2021-10-08T15:40:39.000Z
/* * (C) Copyright 2017-2018 UCAR * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. */ #ifndef UFO_MARINE_INSITUTEMPERATURE_OBSINSITUTEMPERATURE_INTERFACE_H_ #define UFO_MARINE_INSITUTEMPERATURE_OBSINSITUTEMPERATURE_INTERFACE_H_ #include "ioda/ObsSpace.h" #include "ufo/Fortran.h" namespace ufo { /// Interface to Fortran UFO marine/insitutemperature routines extern "C" { // ----------------------------------------------------------------------------- void ufo_insitutemperature_setup_f90(F90hop &, const eckit::Configuration &); void ufo_insitutemperature_delete_f90(F90hop &); void ufo_insitutemperature_simobs_f90(const F90hop &, const F90goms &, const ioda::ObsSpace &, const int &, double &); // ----------------------------------------------------------------------------- } // extern C } // namespace ufo #endif // UFO_MARINE_INSITUTEMPERATURE_OBSINSITUTEMPERATURE_INTERFACE_H_
30.705882
96
0.636015
3ac15b37874278b2cf04d340df9b701a9d36c91a
36,287
h
C
PCD_main/Supp_Func.h
Decclo/Project_ChickenDoor
723cdcaeff2a14dadac0be077fd725a4a587588f
[ "MIT" ]
1
2019-01-06T23:20:05.000Z
2019-01-06T23:20:05.000Z
PCD_main/Supp_Func.h
Decclo/Project_ChickenDoor
723cdcaeff2a14dadac0be077fd725a4a587588f
[ "MIT" ]
null
null
null
PCD_main/Supp_Func.h
Decclo/Project_ChickenDoor
723cdcaeff2a14dadac0be077fd725a4a587588f
[ "MIT" ]
null
null
null
#ifndef Supp_Func #define Supp_Func /* * Supp_Func.h * Author: Hans V. Rasmussen * Created: 13/06-2017 18:47 * Modified: 30/07-2017 16:32 * Version: 1.2 * * Description: * This library includes some extra functionality for the DS3231. */ //Change log /* Version: 1.2 Added: Changed: - Minor changes to relay functions and UI. - Optimized timer1. - Wrote comments for everything besides UIupdate. Removed: Notes: - Running initial tests, preparing for a full scale test. UI will be finished before PCD v1.0 Version: 1.1 Added: - UIupdate in Human_Machine_Interface - EEPROM functionality - Alarm1 and 2 are stored in EEPROM simultaneously with being written to the DS3231 - LCD functionality - UI functionality (Work In Progress) - Added timer1 to make interrupt ever 1 ms - Added counter for relayArray to make relays turn off after x seconds - Added timer for UI to make a 300ms delay as a safety against the user - Added the button read function to the timer, so that the UI is more smooth. Hopefully this will not make any complications. - class relayArray to control the relays Changed: Removed: Notes: Version: 1.0 Added: - classes 'Human_Machine_Interface' and 'DS3231RTC_Alarms' Changed: Removed: Notes: - First working version */ #include <avr/eeprom.h> #include <DS3232RTC.h> //http://github.com/JChristensen/DS3232RTC #include <Streaming.h> //http://arduiniana.org/libraries/streaming/ #include <TimeLib.h> //http://playground.arduino.cc/Code/Time #include <Wire.h> //http://arduino.cc/en/Reference/Wire #include <LiquidCrystal.h> // Arduino library for LCD #include <avr/interrupt.h> // Define Buttons for LCD #define btnPIN A0 #define btnRESET 0 #define btnSELECT 1 #define btnRIGHT 2 #define btnUP 3 #define btnDOWN 4 #define btnLEFT 5 // Define time to wait between buttons presses (change this time to tune the button handling) #define UIbtnHold 500 // Define commands for Relay Array #define liftSTOP 0 // Stops the lift #define liftCW 1 // Opens the door - Retracts in the cable #define liftCCW 2 // Closes the door - Extends the cable // define pins of Relay Array #define RAControl1 DDD4 #define RAControl2 DDD5 #define RAControl3 DDD6 #define RAControl4 DDD7 // Define time for Relay Array to stop lift again (ms) #define RAHold 4000 // Declare external global lcd extern LiquidCrystal lcd; extern DS3232RTC RTC; // Global variables: volatile boolean alarmIsrWasCalled = false; // Variable to check if the interrupt has happened. // UI: volatile uint8_t btnStat = 0; // variable for testing button state every 1 ms. volatile uint16_t UIdelay = 0; volatile boolean UIdelayStat = 0; // relayArray: volatile uint16_t RACounter1 = 0; volatile boolean RACounter1Status = 0; // Debugging: // volatile uint16_t T1Timer = 0; // volatile uint8_t test = 0; // addresses of the alarms on the EEPROM (one time_t object takes 7 bytes) uint8_t alarm1_addr = 0; uint8_t alarm2_addr = 10; // Functions: void alarmIsr() // INT0 triggered function. { alarmIsrWasCalled = true; } // Classes class Human_Machine_Interface { public: Human_Machine_Interface(); /** * \brief Takes in variable of type time_t and prints contents to serial or LCD. * Text is 20 characters long. * * \param t * * \return void */ void printDateTime(time_t t); /** * \brief Takes in variable of type tmElements_t and prints contents to serial or LCD. * Does not print year, text is 15 characters long. * * \param TM * * \return void */ void printDateTime(tmElements_t TM); /** * \brief Checks LCD buttons and returns value corresponding to button. * * \param void * * \return uint8_t */ uint8_t read_LCD_buttons(void); /** * \brief handles user input/output, should be called regurlarly * * \param void * * \return void */ void UIupdate(void); protected: private: uint8_t UIstate; tmElements_t tid; }; class DS3231RTC_Alarms { public: DS3231RTC_Alarms(); // Constructor /** * \brief Initializes the alarms and the interrupt. * * \param * * \return void */ void init_alarms(void); /** * \brief Takes in pointer, checks whether alarm1 or alarm2 have been triggered. * * \param uint8_t * * * \return void */ void alarm_Check(uint8_t *stat); /** * \brief returns the time when alarm1 is expected * * \param void * * \return time_t */ time_t alarm1_get(void); /** * \brief returns the time when alarm2 is expected * * \param void * * \return time_t */ time_t alarm2_get(void); /** * \brief Takes in tmElements_t and sets timer1 to trigger once a day. * Only uses seconds, minutes and hours. * * \param TM * * \return boolean */ void alarm1_set(tmElements_t TM); /** * \brief Takes in tmElements_t and sets timer2 to trigger once a day. * Only uses seconds, minutes and hours. * * \param TM * * \return boolean */ void alarm2_set(tmElements_t TM); /************************************************************************ To change alarms do the following: RTC.setAlarm(ALM1_MATCH_SECONDS, 0, 0, 0, 1); //daydate parameter should be between 1 and 7 RTC.alarm(ALARM_1); //ensure RTC interrupt flag is cleared RTC.alarmInterrupt(ALARM_1, true); RTC.setAlarm syntax for alarm1 is void setAlarm(ALARM_TYPES_t alarmType, byte seconds, byte minutes, byte hours, byte daydate); RTC.setAlarm syntax for alarm2 is void setAlarm(ALARM_TYPES_t alarmType, byte minutes, byte hours, byte daydate); Values for Alarm 1 ALM1_EVERY_SECOND -- causes an alarm once per second. ALM1_MATCH_SECONDS -- causes an alarm when the seconds match (i.e. once per minute). ALM1_MATCH_MINUTES -- causes an alarm when the minutes and seconds match. ALM1_MATCH_HOURS -- causes an alarm when the hours and minutes and seconds match. ALM1_MATCH_DATE -- causes an alarm when the date of the month and hours and minutes and seconds match. ALM1_MATCH_DAY -- causes an alarm when the day of the week and hours and minutes and seconds match. Values for Alarm 2 ALM2_EVERY_MINUTE -- causes an alarm once per minute. ALM2_MATCH_MINUTES -- causes an alarm when the minutes match (i.e. once per hour). ALM2_MATCH_HOURS -- causes an alarm when the hours and minutes match. ALM2_MATCH_DATE -- causes an alarm when the date of the month and hours and minutes match. ALM2_MATCH_DAY -- causes an alarm when the day of the week and hours and minutes match. ************************************************************************/ protected: private: // union: make a variable that can be interpreted multiple ways, ex as a long int or as an array of 8 bytes. // This will be used when writing time_t to the EEPROM, as the EEPROM with current libraries only takes chars to store. // By using union one can easily split the unsigned long int time_t into 8 bytes of data and then write them, example: // union_name.long_variable = makeTime(TM); // for (int i = 0; i < 7; i++) // { // eeprom_write_byte((uint8_t *)alarm1_addr+i, u.byte_array[0+i]); // } union { unsigned long int long_time; byte byte_array[7]; } alarm1_time; union { unsigned long int long_time; byte byte_array[7]; } alarm2_time; }; class liftRelayArray { public: liftRelayArray(); // Constructor /** * \brief Initializes the pins required * * \param void * * \return void */ void relayArrayInit(void); /** * \brief Executes a command for the lift * * \param cmd - liftCW, liftCCW, liftSTOP * * \return void */ void relayArrayCommand(uint8_t cmd); /** * \brief Function that controls what actually should happen when alarm happens. * * \param uint8_t alarmtrig * * \return void */ void relayAutoCommand(uint8_t alarmtrig); protected: private: }; // make objects of the classes: Human_Machine_Interface HMI;// Make a object of the 'class Human_Machine_Interface' named 'HMI' DS3231RTC_Alarms RTC_alarm; // Make a object of the 'class DS3231RTC_Alarms' named 'RTC_alarm' liftRelayArray relayArray; // Make a object of the 'class liftRelayArray' named 'relayArray' Human_Machine_Interface::Human_Machine_Interface() : UIstate(0) { breakTime(0, tid); // Standard constructor procedure: // give variables values by constructor : var_name(var_val) {} // old constructor code // UIstate = 0; // time_t temp = 0; // tid = HMI.ConvTotm(temp); // tid.Hour = 8; // tid.Minute = 30; } void Human_Machine_Interface::printDateTime(time_t t) { // Print the current time to serial with time_t as input. Serial << ((day(t)<10) ? "0" : "") << _DEC(day(t)) << ' '; Serial << (month(t)) << " " << _DEC(year(t)) << ' '; Serial << ((hour(t)<10) ? "0" : "") << _DEC(hour(t)) << ':'; Serial << ((minute(t)<10) ? "0" : "") << _DEC(minute(t)) << ':'; Serial << ((second(t)<10) ? "0" : "") << _DEC(second(t)); } void Human_Machine_Interface::printDateTime(tmElements_t TM) { // Print the current time to serial with tmElements_t as input. Serial << ((TM.Day<10) ? "0" : "") << TM.Day << ' '; Serial << (TM.Month) << ' '; Serial << ((TM.Hour<10) ? "0" : "") << TM.Hour << ':'; Serial << ((TM.Minute<10) ? "0" : "") << TM.Minute << ':'; Serial << ((TM.Second<10) ? "0" : "") << TM.Second << endl; } uint8_t Human_Machine_Interface::read_LCD_buttons(void) { // read the value from the sensor int adc_key_in = analogRead(btnPIN); if (adc_key_in > 1050) return btnRESET; if (adc_key_in < 50) return btnRIGHT; if (adc_key_in < 250) return btnUP; if (adc_key_in < 450) return btnDOWN; if (adc_key_in < 650) return btnLEFT; if (adc_key_in < 850) return btnSELECT; return 0; // when all others fail, return 0. } void Human_Machine_Interface::UIupdate(void) { uint8_t userState = 0; if (UIdelay >= UIbtnHold) { UIdelay = 0; UIdelayStat = 0; userState = btnStat; // insert user input here. btnStat = 0; } else { UIdelayStat = 1; } // userState = HMI.read_LCD_buttons(); switch (UIstate) { case 0: // Update tid with time from DS3231 breakTime(RTC.get(), tid); // Print time here on LCD lcd.noBlink(); lcd.clear(); lcd.setCursor(0,0); lcd << "Klokkeslaet"; lcd.setCursor(0,1); lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << ""; // user input switch (userState) { case btnSELECT: /* Your code here */ // Go to UIstate 1, To change C1 UIstate = 1; break; case btnRESET: /* Your code here */ //Nothing happens break; case btnUP: /* Your code here */ //nothing happens break; case btnDOWN: /* Your code here */ //nothing happens break; case btnLEFT: /* Your code here */ //Go to UIstate 20, we go to alarm 2 UIstate = 20; break; case btnRIGHT: /* Your code here */ //Go to UIstate 10, we go to alarm 1 UIstate = 10; break; default: /* Your code here */ break; } break; case 1: // Show time, blink C1 lcd.clear(); lcd.setCursor(0,0); lcd << "Skift Klokkeslet"; lcd.setCursor(0,1); lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << ""; lcd.setCursor(0,1); lcd.blink(); switch (userState) { case btnSELECT: /* Your code here */ //Do nothing break; case btnRESET: /* Your code here */ //Do nothing break; case btnUP: /* Your code here */ //Add 10 to variable hours //If variable hours is 23< then subtract 20 if ((0 <= tid.Hour) & (tid.Hour < 14)) { tid.Hour += 10; } else if((14 <= tid.Hour) & (tid.Hour < 20)) { tid.Hour -= 10; } else { tid.Hour -= 20; } break; case btnDOWN: /* Your code here */ //subtract 10 to variable hours // If variable hours is <0 then add 20 if ((0 <= tid.Hour) & (tid.Hour < 4)) { tid.Hour += 20; } else if((4 <= tid.Hour) & (tid.Hour < 10)) { tid.Hour += 10; } else { tid.Hour -= 10; } break; case btnLEFT: /* Your code here */ //Go to UIstate 0, revert changes, see time UIstate = 0; break; case btnRIGHT: /* Your code here */ //Go to UIstate 2, To change C2 UIstate = 2; break; default: /* Your code here */ break; } break; case 2: // Show time, blink C2 lcd.clear(); lcd.setCursor(0,0); lcd << "Skift Klokkeslet"; lcd.setCursor(0,1); lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << ""; lcd.setCursor(1,1); lcd.blink(); switch (userState) { case btnSELECT: /* Your code here */ //Do nothing break; case btnRESET: /* Your code here */ //Do nothing break; case btnUP: /* Your code here */ //Add 1 to variable hours //If variable hours is 23< then subtract 3 if ((9 == tid.Hour) | (19 == tid.Hour)) { tid.Hour -= 9; } else if(23 == tid.Hour) { tid.Hour -= 3; } else { tid.Hour += 1; } break; case btnDOWN: /* Your code here */ //subtract 1 to variable hours // If variable hours is <0 then add 9 if ((0 == tid.Hour) | (10 == tid.Hour)) { tid.Hour += 9; } else if(20 == tid.Hour) { tid.Hour += 3; } else { tid.Hour -= 1; } break; case btnLEFT: /* Your code here */ //Go to UIstate 1, to change C1 UIstate = 1; break; case btnRIGHT: /* Your code here */ // Go to UIstate 3, To change C3 UIstate = 3; break; default: /* Your code here */ break; } break; case 3: // Show time, blink C3 lcd.clear(); lcd.setCursor(0,0); lcd << "Skift Klokkeslet"; lcd.setCursor(0,1); lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << ""; lcd.setCursor(3,1); lcd.blink(); switch (userState) { case btnSELECT: /* Your code here */ // Do nothing break; case btnRESET: /* Your code here */ //Do nothing break; case btnUP: /* Your code here */ //Add 10 to variable minutes //If variable minutes is 59< then subtract 50 if ((50 <= tid.Minute)) { tid.Minute -= 50; } else { tid.Minute += 10; } break; case btnDOWN: /* Your code here */ //subtract 10 to variable minutes // If variable minutes is <0 then add 50 if((0 <= tid.Minute) & (tid.Minute < 10)) { tid.Minute += 50; } else { tid.Minute -= 10; } break; case btnLEFT: /* Your code here */ //Go to UIstate 2, to change C2 UIstate = 2; break; case btnRIGHT: /* Your code here */ //Go to UIstate 4, To change C4 UIstate = 4; break; default: /* Your code here */ break; } break; case 4: // Show time, blink C4 lcd.clear(); lcd.setCursor(0,0); lcd << "Skift Klokkeslet"; lcd.setCursor(0,1); lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << ""; lcd.setCursor(4,1); lcd.blink(); switch (userState) { case btnSELECT: /* Your code here */ // Go to UIstate 0, write time to timer module, UIstate = 0; RTC.set(makeTime(tid)); break; case btnRESET: /* Your code here */ //Do nothing break; case btnUP: /* Your code here */ //Add 1 to variable minutes //If variable minutes is 59< then subtract 9 if ((tid.Minute == 9) | (tid.Minute == 19) | (tid.Minute == 29) | (tid.Minute == 39) | (tid.Minute == 49) | (tid.Minute == 59)) { tid.Minute -= 9; } else { tid.Minute += 1; } break; case btnDOWN: /* Your code here */ //subtract 1 to variable minutes // If variable minutes is >0 then add 9 if ((tid.Minute == 0) | (tid.Minute == 10) | (tid.Minute == 20) | (tid.Minute == 30) | (tid.Minute == 40) | (tid.Minute == 50)) { tid.Minute += 9; } else { tid.Minute -= 1; } break; case btnLEFT: /* Your code here */ //Go to UIstate 3, to change C3 UIstate = 3; break; case btnRIGHT: /* Your code here */ //Do nothing break; default: /* Your code here */ break; } break; case 10: // Show Alarm1 breakTime(RTC_alarm.alarm1_get(), tid); lcd.noBlink(); lcd.clear(); lcd.setCursor(0,0); lcd << "Doeren aabner:"; lcd.setCursor(0,1); lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << ""; switch (userState) { case btnSELECT: /* Your code here */ // Go to UIstate 11, to change C1 UIstate = 11; break; case btnRESET: /* Your code here */ //Do nothing break; case btnUP: /* Your code here */ //Do nothing break; case btnDOWN: /* Your code here */ //Do nothing break; case btnLEFT: /* Your code here */ //Go to UIstate 0, we go to Time UIstate = 0; break; case btnRIGHT: /* Your code here */ //Go to UIstate 20, we go to Alarm2 UIstate = 20; break; default: /* Your code here */ break; } break; case 11: // Show Alarm1, blink C1 lcd.clear(); lcd.setCursor(0,0); lcd << "Skift aabning:"; lcd.setCursor(0,1); lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << ""; lcd.setCursor(0,1); lcd.blink(); switch (userState) { case btnSELECT: /* Your code here */ //Do nothing break; case btnRESET: /* Your code here */ //Do nothing break; case btnUP: /* Your code here */ //Add 10 to variable hours //If variable hours is 23< then subtract 20 if ((0 <= tid.Hour) & (tid.Hour < 14)) { tid.Hour += 10; } else if((14 <= tid.Hour) & (tid.Hour < 20)) { tid.Hour -= 10; } else { tid.Hour -= 20; } break; case btnDOWN: /* Your code here */ //subtract 10 to variable hours // If variable hours is <0 then add 20 if ((0 <= tid.Hour) & (tid.Hour < 4)) { tid.Hour += 20; } else if((4 <= tid.Hour) & (tid.Hour < 10)) { tid.Hour += 10; } else { tid.Hour -= 10; } break; case btnLEFT: /* Your code here */ //Go to UIstate 10, revert changes, see alarm1 UIstate = 10; break; case btnRIGHT: /* Your code here */ // Go to UIstate 12, To change C2 UIstate = 12; break; default: /* Your code here */ break; } break; case 12: // Show Alarm1, blink C2 lcd.clear(); lcd.setCursor(0,0); lcd << "Skift aabning:"; lcd.setCursor(0,1); lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << ""; lcd.setCursor(1,1); lcd.blink(); switch (userState) { case btnSELECT: /* Your code here */ //Do nothing break; case btnRESET: /* Your code here */ //Do nothing break; case btnUP: /* Your code here */ //Add 1 to variable hours //If variable hours is 23< then subtract 3 if ((9 == tid.Hour) | (19 == tid.Hour)) { tid.Hour -= 9; } else if(23 == tid.Hour) { tid.Hour -= 3; } else { tid.Hour += 1; } break; case btnDOWN: /* Your code here */ //subtract 1 to variable hours // If variable hours is <0 then add 9 if ((0 == tid.Hour) | (10 == tid.Hour)) { tid.Hour += 9; } else if(20 == tid.Hour) { tid.Hour += 3; } else { tid.Hour -= 1; } break; case btnLEFT: /* Your code here */ //Go to UIstate 11, To change C1 UIstate = 11; break; case btnRIGHT: /* Your code here */ // Go to UIstate 13, To change C3 UIstate = 13; break; default: /* Your code here */ break; } break; case 13: // Show Alarm1, blink C3 lcd.clear(); lcd.setCursor(0,0); lcd << "Skift aabning:"; lcd.setCursor(0,1); lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << ""; lcd.setCursor(3,1); lcd.blink(); switch (userState) { case btnSELECT: /* Your code here */ // Go to UIstate 14, To change C4 break; case btnRESET: /* Your code here */ //Go to UIstate 12, To change C2 break; case btnUP: /* Your code here */ //Add 10 to variable minutes //If variable minutes is 59< then subtract 50 if ((50 <= tid.Minute)) { tid.Minute -= 50; } else { tid.Minute += 10; } break; case btnDOWN: /* Your code here */ //subtract 10 to variable minutes // If variable minutes is <0 then add 50 if((0 <= tid.Minute) & (tid.Minute < 10)) { tid.Minute += 50; } else { tid.Minute -= 10; } break; case btnLEFT: /* Your code here */ //Do nothing UIstate = 12; break; case btnRIGHT: /* Your code here */ //Do nothing UIstate = 14; break; default: /* Your code here */ break; } break; case 14: // Show Alarm1, blink C4 lcd.clear(); lcd.setCursor(0,0); lcd << "Skift aabning:"; lcd.setCursor(0,1); lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << ""; lcd.setCursor(4,1); lcd.blink(); switch (userState) { case btnSELECT: /* Your code here */ // Go to UIstate 10, Write Alarm1 to timer module UIstate = 10; RTC_alarm.alarm1_set(tid); break; case btnRESET: /* Your code here */ //Go to UIstate 13, To change C3 break; case btnUP: /* Your code here */ //Add 1 to variable minutes //If variable minutes is 59< then subtract 9 if ((tid.Minute == 9) | (tid.Minute == 19) | (tid.Minute == 29) | (tid.Minute == 39) | (tid.Minute == 49) | (tid.Minute == 59)) { tid.Minute -= 9; } else { tid.Minute += 1; } break; case btnDOWN: /* Your code here */ //subtract 1 to variable minutes // If variable minutes is >0 then add 9 if ((tid.Minute == 0) | (tid.Minute == 10) | (tid.Minute == 20) | (tid.Minute == 30) | (tid.Minute == 40) | (tid.Minute == 50)) { tid.Minute += 9; } else { tid.Minute -= 1; } break; case btnLEFT: /* Your code here */ //Go to UIstate 3, to change C3 UIstate = 13; break; case btnRIGHT: /* Your code here */ //Do nothing break; default: /* Your code here */ break; } break; case 20: // Show Alarm2 breakTime(RTC_alarm.alarm2_get(), tid); lcd.noBlink(); lcd.clear(); lcd.setCursor(0,0); lcd << "Doeren Lukker:"; lcd.setCursor(0,1); lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << ""; switch (userState) { case btnSELECT: /* Your code here */ // Go to UIstate 21, To change C1 UIstate = 21; break; case btnRESET: /* Your code here */ //Do nothing break; case btnUP: /* Your code here */ //Do nothing break; case btnDOWN: /* Your code here */ //Do nothing break; case btnLEFT: /* Your code here */ //Go to UIstate 10, we go to Alarm1 UIstate = 10; break; case btnRIGHT: /* Your code here */ //Go to UIstate 0, we go to Time UIstate = 0; break; default: /* Your code here */ break; } break; case 21: // Show Alarm2, blink C1 lcd.clear(); lcd.setCursor(0,0); lcd << "Skift lukketid:"; lcd.setCursor(0,1); lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << ""; lcd.setCursor(0,1); lcd.blink(); switch (userState) { case btnSELECT: /* Your code here */ // Do nothing break; case btnRESET: /* Your code here */ // Do nothing break; case btnUP: /* Your code here */ //Add 10 to variable hours //If variable hours is 23< then subtract 20 if ((0 <= tid.Hour) & (tid.Hour < 14)) { tid.Hour += 10; } else if((14 <= tid.Hour) & (tid.Hour < 20)) { tid.Hour -= 10; } else { tid.Hour -= 20; } break; case btnDOWN: /* Your code here */ //subtract 10 to variable hours // If variable hours is <0 then add 20 if ((0 <= tid.Hour) & (tid.Hour < 4)) { tid.Hour += 20; } else if((4 <= tid.Hour) & (tid.Hour < 10)) { tid.Hour += 10; } else { tid.Hour -= 10; } break; case btnLEFT: /* Your code here */ //Go to UIstate 20, revert changes, see Alarm2 UIstate = 20; break; case btnRIGHT: /* Your code here */ //Go to UIstate 22 UIstate = 22; break; default: /* Your code here */ break; } break; case 22: // Show Alarm2, blink C2 lcd.clear(); lcd.setCursor(0,0); lcd << "Skift lukketid:"; lcd.setCursor(0,1); lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << ""; lcd.setCursor(1,1); lcd.blink(); switch (userState) { case btnSELECT: /* Your code here */ // Do nothing break; case btnRESET: /* Your code here */ // Do nothing break; case btnUP: /* Your code here */ //Add 1 to variable hours //If variable hours is 23< then subtract 3 if ((9 == tid.Hour) | (19 == tid.Hour)) { tid.Hour -= 9; } else if(23 == tid.Hour) { tid.Hour -= 3; } else { tid.Hour += 1; } break; case btnDOWN: /* Your code here */ //subtract 1 to variable hours // If variable hours is <0 then add 9 if ((0 == tid.Hour) | (10 == tid.Hour)) { tid.Hour += 9; } else if(20 == tid.Hour) { tid.Hour += 3; } else { tid.Hour -= 1; } break; case btnLEFT: /* Your code here */ //Go to UIstate 21 to change C1 UIstate = 21; break; case btnRIGHT: /* Your code here */ //Go to UIstate 23 to change C3 UIstate = 23; break; default: /* Your code here */ break; } break; case 23: // Show Alarm2, blink C3 lcd.clear(); lcd.setCursor(0,0); lcd << "Skift lukketid:"; lcd.setCursor(0,1); lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << ""; lcd.setCursor(3,1); lcd.blink(); switch (userState) { case btnSELECT: /* Your code here */ // Do nothing break; case btnRESET: /* Your code here */ // Do nothing break; case btnUP: /* Your code here */ //Add 10 to variable minutes //If variable minutes is 59< then subtract 50 if ((50 <= tid.Minute)) { tid.Minute -= 50; } else { tid.Minute += 10; } break; case btnDOWN: /* Your code here */ //subtract 10 to variable minutes // If variable minutes is <0 then add 50 if((0 <= tid.Minute) & (tid.Minute < 10)) { tid.Minute += 50; } else { tid.Minute -= 10; } break; case btnLEFT: /* Your code here */ // Go to UIstate 22 to change C2 UIstate = 22; break; case btnRIGHT: /* Your code here */ // Go to UIstate 24 to change C4 UIstate = 24; break; default: /* Your code here */ break; } break; case 24: // Show Alarm2, blink C4 lcd.clear(); lcd.setCursor(0,0); lcd << "Skift lukketid:"; lcd.setCursor(0,1); lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << ""; lcd.setCursor(4,1); lcd.blink(); switch (userState) { case btnSELECT: /* Your code here */ // Go to UIstate 20, Write Alarm2 to timer module UIstate = 20; RTC_alarm.alarm2_set(tid); break; case btnRESET: /* Your code here */ // Do nothing break; case btnUP: /* Your code here */ //Add 1 to variable minutes //If variable minutes is 59< then subtract 9 if ((tid.Minute == 9) | (tid.Minute == 19) | (tid.Minute == 29) | (tid.Minute == 39) | (tid.Minute == 49) | (tid.Minute == 59)) { tid.Minute -= 9; } else { tid.Minute += 1; } break; case btnDOWN: /* Your code here */ //subtract 1 to variable minutes // If variable minutes is >0 then add 9 if ((tid.Minute == 0) | (tid.Minute == 10) | (tid.Minute == 20) | (tid.Minute == 30) | (tid.Minute == 40) | (tid.Minute == 50)) { tid.Minute += 9; } else { tid.Minute -= 1; } break; case btnLEFT: /* Your code here */ // Go to UIstate 23 to change C3 UIstate = 23; break; case btnRIGHT: /* Your code here */ // Do nothing break; default: /* Your code here */ break; } break; default: // default state, aka state 0. // user input break; } } DS3231RTC_Alarms::DS3231RTC_Alarms() { // Constructor for the alarms class. alarm1_time.long_time = 0; alarm2_time.long_time = 0; } void DS3231RTC_Alarms::init_alarms(void) { // Setup the SQW interrupt: DDRD &= ~(1 << DDD2); // make INT0 an input. PORTD |= (1 << DDD2); // enable pull-up on INT0. attachInterrupt(INT0, alarmIsr, FALLING); // Initializing the INT0 interrupt in the Arduino way. //Disable the default square wave of the SQW pin. RTC.squareWave(SQWAVE_NONE); //Prepare alarm1 for the interrupt. RTC.alarm(ALARM_1); //ensure RTC interrupt flag is cleared RTC.alarmInterrupt(ALARM_1, true); //Prepare alarm1 for the interrupt. RTC.alarm(ALARM_2); //ensure RTC interrupt flag is cleared RTC.alarmInterrupt(ALARM_2, true); // Read the alarm time from the EEPROM for UI use for (int i = 0; i < 7; i++) { DS3231RTC_Alarms::alarm1_time.byte_array[0+i] = eeprom_read_byte((uint8_t *)alarm1_addr+i); } for (int i = 0; i < 7; i++) { DS3231RTC_Alarms::alarm2_time.byte_array[0+i] = eeprom_read_byte((uint8_t *)alarm2_addr+i); } } void DS3231RTC_Alarms::alarm_Check(uint8_t *stat) { if (alarmIsrWasCalled) // if the interrupt has happened { if (RTC.alarm(ALARM_1)) // check if alarm1 has happened and reset it. { *stat = 1; } else if (RTC.alarm(ALARM_2)) // or else check if alarm2 has happened and reset it. { *stat = 2; } alarmIsrWasCalled = false; } else // else return 0 { *stat = 0; } } time_t DS3231RTC_Alarms::alarm1_get(void) { // returns the value from alarm1 read from the EEPROM during setup return alarm1_time.long_time; } time_t DS3231RTC_Alarms::alarm2_get(void) { // returns the value from alarm2 read from the EEPROM during setup return alarm2_time.long_time; } void DS3231RTC_Alarms::alarm1_set(tmElements_t TM) { // Overwrites the current alarm1 both in the DS3231 clock module and in the EEPROM. // Overwrite the alarm1 time in the DS3231 clock module. RTC.setAlarm(ALM1_MATCH_HOURS, TM.Second, TM.Minute, TM.Hour, 1); //daydate parameter should be between 1 and 7 RTC.alarm(ALARM_1); //ensure RTC interrupt flag is cleared RTC.alarmInterrupt(ALARM_1, true); // Overwrite the alarm1 time in the EEPROM. alarm1_time.long_time = makeTime(TM); for (int i = 0; i < 7; i++) { eeprom_write_byte((uint8_t *)alarm1_addr+i, alarm1_time.byte_array[0+i]); } // Writing debug message to serial Serial << "Alarm1 set to " << alarm1_time.long_time << " or "; Serial << TM.Hour << ":" << TM.Minute << ":" << TM.Second << endl; } void DS3231RTC_Alarms::alarm2_set(tmElements_t TM) { // Overwrites the current alarm2 both in the DS3231 clock module and in the EEPROM. // Overwrite the alarm2 time in the DS3231 clock module. RTC.setAlarm(ALM2_MATCH_HOURS, TM.Second, TM.Minute, TM.Hour, 1); //daydate parameter should be between 1 and 7 RTC.alarm(ALARM_2); //ensure RTC interrupt flag is cleared RTC.alarmInterrupt(ALARM_2, true); // Overwrite the alarm2 time in the EEPROM. alarm2_time.long_time = makeTime(TM); for (int i = 0; i < 7; i++) { eeprom_write_byte((uint8_t *)alarm2_addr+i, alarm2_time.byte_array[0+i]); } // Writing debug message to serial Serial << "Alarm2 set to " << alarm2_time.long_time << " or "; Serial << TM.Hour << ":" << TM.Minute << ":" << TM.Second << endl; } liftRelayArray::liftRelayArray() { // Constructor for the relay class } void liftRelayArray::relayArrayInit(void) { // Initialize Buttons DDRD |= (1 << RAControl1) | (1 << RAControl2) | (1 << RAControl3) | (1 << RAControl4); // Marks pins as output. //PORTD &= ~(1 << RAControl1) & ~(1 << RAControl2) & ~(1 << RAControl3) & ~(1 << RAControl4); // Puts pins into off state. PORTD |= (1 << RAControl1) | (1 << RAControl2) | (1 << RAControl3) | (1 << RAControl4); /* Use ports: PORTD |= (1 << DDC1); // Make PD1 = 1 (on) PORTD &= ~(1 << DDC1); // Puts PD1 = 0 (off). */ // setup timer1 to make an interrupt every 1 ms noInterrupts(); // disable all interrupts TCCR1A = 0; TCCR1B = 0; TCNT1 = 0; OCR1A = 16000; // compare match register 16MHz/1000 TCCR1B |= (1 << WGM12); // CTC mode TCCR1B |= (1 << CS10); // No prescaler TIMSK1 |= (1 << OCIE1A); // enable timer compare interrupt interrupts(); // enable all interrupts } void liftRelayArray::relayArrayCommand(uint8_t cmd) { // Using the lift made easy. switch (cmd) { case liftCW: // Make the cable retract - Open door /* PORTD &= ~(1 << RAControl1); // Turn off all relays PORTD &= ~(1 << RAControl2); PORTD &= ~(1 << RAControl3); PORTD &= ~(1 << RAControl4); delay(10); PORTD |= (1 << RAControl1); // Turn on lift PORTD |= (1 << RAControl4); */ PORTD |= (1 << RAControl1); // Turn off all relays PORTD |= (1 << RAControl2); PORTD |= (1 << RAControl3); PORTD |= (1 << RAControl4); _delay_ms(10); PORTD &= ~(1 << RAControl1); // Turn on lift PORTD &= ~(1 << RAControl4); break; case liftCCW: // Make the cable extend - Close door /* PORTD &= ~(1 << RAControl1); // Turn off all relays PORTD &= ~(1 << RAControl2); PORTD &= ~(1 << RAControl3); PORTD &= ~(1 << RAControl4); delay(10); PORTD |= (1 << RAControl2); // Turn on lift PORTD |= (1 << RAControl3); */ PORTD |= (1 << RAControl1); // Turn off all relays PORTD |= (1 << RAControl2); PORTD |= (1 << RAControl3); PORTD |= (1 << RAControl4); _delay_ms(10); PORTD &= ~(1 << RAControl2); // Turn on lift PORTD &= ~(1 << RAControl3); break; default: // default, aka. liftSTOP PORTD |= (1 << RAControl1); // Turn off all relays PORTD |= (1 << RAControl2); PORTD |= (1 << RAControl3); PORTD |= (1 << RAControl4); break; } } void liftRelayArray::relayAutoCommand(uint8_t alarmtrig) { switch(alarmtrig) // switch statement to automatically handle what should happen if alarm has happened. { case 1: // alarm1: if(!RACounter1Status) { relayArrayCommand(liftCW); RACounter1Status = 1; // start timer and stop after x seconds (see defines) } break; case 2: // alarm2: if(!RACounter1Status) { relayArrayCommand(liftCCW); RACounter1Status = 1; // start timer and stop after x seconds (see defines) } break; default: // if there was no alarm: if (RACounter1 >= RAHold) { relayArrayCommand(liftSTOP); RACounter1Status = 0; RACounter1 = 0; // Reset RACounter1. } break; } } ISR(TIMER1_COMPA_vect) // timer compare interrupt service routine { // // Debugging // if (T1Timer >= 1000) // { // test++; // T1Timer = 0; // // Serial << "Test is: " << test << " and RACounter is: " << RACounter1 << endl; // } // else // { // T1Timer++; // } // HMI interface timers: if (!btnStat) { btnStat = HMI.read_LCD_buttons(); } if (UIdelayStat == 1) { UIdelay++; } // RelayArray: if (RACounter1Status == 1) { RACounter1++; } } #endif
22.344212
131
0.580676
1690f9bc88b30859394dc9af847c6d5298cd20b8
390
h
C
sonarr-ios/API/Models/SNRData.h
hhs4harry/sonarr-ios
9ebefee400f58ecbfd4beb53d4ffdd63d0a71f12
[ "MIT" ]
2
2017-03-28T06:48:01.000Z
2020-02-08T07:31:35.000Z
sonarr-ios/API/Models/SNRData.h
hhs4harry/sonarr-ios
9ebefee400f58ecbfd4beb53d4ffdd63d0a71f12
[ "MIT" ]
null
null
null
sonarr-ios/API/Models/SNRData.h
hhs4harry/sonarr-ios
9ebefee400f58ecbfd4beb53d4ffdd63d0a71f12
[ "MIT" ]
null
null
null
// // SNRData.h // sonarr-ios // // Created by Harry Singh on 26/02/17. // Copyright © 2017 Harry Singh. All rights reserved. // #import <JSONModel/JSONModel.h> @interface SNRData : JSONModel @property (copy, nonatomic) NSString<Optional> *downloadClient; @property (copy, nonatomic) NSString<Optional> *droppedPath; @property (copy, nonatomic) NSString<Optional> *importedPath; @end
24.375
63
0.730769
3d32f8ef18fa0751e0243b82e90da15db0fc57dc
7,503
h
C
DIR819_v1.06/src/kernel/linux-2.6.36.x/drivers/net/eip93_drivers/quickSec/src/ipsec/hwaccel/safenet_pe/safenet_405ex_gpio.h
Sirherobrine23/Dir819gpl_code
8af92d65416198755974e3247b7bbe7f1151d525
[ "BSD-2-Clause" ]
1
2022-03-19T06:38:01.000Z
2022-03-19T06:38:01.000Z
DIR819_v1.06/src/kernel/linux-2.6.36.x/drivers/net/eip93_drivers/quickSec/src/ipsec/hwaccel/safenet_pe/safenet_405ex_gpio.h
Sirherobrine23/Dir819gpl_code
8af92d65416198755974e3247b7bbe7f1151d525
[ "BSD-2-Clause" ]
null
null
null
DIR819_v1.06/src/kernel/linux-2.6.36.x/drivers/net/eip93_drivers/quickSec/src/ipsec/hwaccel/safenet_pe/safenet_405ex_gpio.h
Sirherobrine23/Dir819gpl_code
8af92d65416198755974e3247b7bbe7f1151d525
[ "BSD-2-Clause" ]
1
2022-03-19T06:38:03.000Z
2022-03-19T06:38:03.000Z
/*h* * File: safenet_405ex_gpio.h * * 405EX platform GPIO access functions for Linux kernel mode. * * Usage: * * For Initialization: * =================== * * #include safenet_405ex_gpio.h * ... * // call GPIO init function in your initialization routine: * // this step can be skipped, because this function is called automatically * // anyway * // however, if gpio_out functions (see below) are intended to be used in * // atomic context * // (interrupt BHs and THs, softirq), then GPIO init function must be * // called explicitly * // in non-atomic context * safenet_linux_gpio_init(); * ... * * For using during testing: * ========================= * * #include safenet_405ex_gpio.h * ... * // call GPIO out function: * safenet_linux_gpio_out_high(4); * * // some code you'd like to measure: * ... * * safenet_linux_gpio_out_low(4); * ... * * Note: For testing purposes it is possible to use GPIO signal numbers * 4-7 and 12-15 when calling safenet_linux_gpio_out. * For Clean-up: * =================== * * #include safenet_405ex_gpio.h * ... * // call GPIO uninit function in your cleanup routine: * // this step is optional, as cleanup is not absolutely neccessary * safenet_linux_gpio_uninit(); * ... * * * Copyright (c) 2007 SafeNet, Inc. All rights reserved. * * The source code provided in this file is licensed perpetually and * royalty-free to the User for exclusive use as sample software to be used in * developing derivative code based on SafeNet products and technologies. The * SafeNet source code shall not be redistributed in part or in whole, nor as * part of any User derivative product containing source code, without the * express written consent of SafeNet. * * * Edit History: * *Initial revision * 14-11-2007 abykov@safenet-inc.com Created. */ #ifndef SAFENET_405EX_GPIO_H #define SAFENET_405EX_GPIO_H #undef SAFENET_DEBUG_USE_GPIO #ifdef SAFENET_DEBUG_USE_GPIO void *gpio_base __attribute__ ((weak)) = NULL; /* Note: For testing purposes it is possible to use GPIO signal numbers 4-7 and 12-15 when calling safenet_linux_gpio_out. */ bool safenet_linux_gpio_init(void) __attribute__ ((weak)); inline void safenet_linux_gpio_out_high(unsigned gpio_sig_num) __attribute__ ((weak)); inline void safenet_linux_gpio_out_low(unsigned gpio_sig_num) __attribute__ ((weak)); void safenet_linux_gpio_out_hard(unsigned gpio_sig_num, bool high) __attribute__ ((weak)); void safenet_linux_gpio_uninit(void) __attribute__ ((weak)); inline void safenet_linux_gpio_out_high(unsigned gpio_sig_num) { ulong val; if (unlikely(!gpio_base)) safenet_linux_gpio_init(); /* bn <= '1' */ val = in_be32((gpio_base+(GPIO0_OR-GPIO_BASE))); out_be32((gpio_base+(GPIO0_OR-GPIO_BASE)), val | 1 << (31-gpio_sig_num) ); } inline void safenet_linux_gpio_out_low(unsigned gpio_sig_num) { ulong val; if (unlikely(!gpio_base)) safenet_linux_gpio_init(); /* bn <= '0' */ val = in_be32((gpio_base+(GPIO0_OR-GPIO_BASE))); out_be32((gpio_base+(GPIO0_OR-GPIO_BASE)), val & ~(1 << (31-gpio_sig_num)) ); } void safenet_linux_gpio_out_hard(unsigned gpio_sig_num, bool high) { ulong val; ulong high_mask; ulong gpio_mask; ulong gpio_sig_num_mask = 1<<gpio_sig_num; static ulong already_called = 0; if (unlikely(gpio_sig_num > 31)) return; if (unlikely(!gpio_base)) { if (net_ratelimit()) printk(KERN_INFO "Safenet linux gpio: Not initialized!\n"); return; } high_mask = 1 << (31-gpio_sig_num); gpio_mask = ~((1 << (31-2*gpio_sig_num)) | (1 << (30-2*gpio_sig_num)) ); /* bn <= '0/1' */ val = in_be32((gpio_base+(GPIO0_OR-GPIO_BASE))); if (high) out_be32((gpio_base+(GPIO0_OR-GPIO_BASE)), val | high_mask ); else out_be32((gpio_base+(GPIO0_OR-GPIO_BASE)), val & ~high_mask ); if (unlikely(!(gpio_sig_num_mask & already_called))) { already_called |= gpio_sig_num_mask; /* ODR: bn <= '0' Enable associate output driver */ val = in_be32((gpio_base+(GPIO0_ODR-GPIO_BASE))); out_be32((gpio_base+(GPIO0_ODR-GPIO_BASE)), val & ~high_mask ); /* TCR: bn <= '1' Enable associate output driver */ val = in_be32((gpio_base+(GPIO0_TCR-GPIO_BASE))); out_be32((gpio_base+(GPIO0_TCR-GPIO_BASE)), val | high_mask ); if (gpio_sig_num < 16) { /* OSRL: b2n,b2n+1 <= '00' select GPIO0_OR */ val = in_be32((gpio_base+(GPIO0_OSRL-GPIO_BASE))); out_be32((gpio_base+(GPIO0_OSRL-GPIO_BASE)), val & gpio_mask); /* TSRL: b2n,b2n+1 <= '00' select TCR */ val = in_be32((gpio_base+(GPIO0_TSRL-GPIO_BASE))); out_be32((gpio_base+(GPIO0_TSRL-GPIO_BASE)), val & gpio_mask); /* ISR1L */ val = in_be32((gpio_base+(GPIO0_ISR1L-GPIO_BASE))); out_be32((gpio_base+(GPIO0_ISR1L-GPIO_BASE)), val & gpio_mask); /* ISR2L */ val = in_be32((gpio_base+(GPIO0_ISR2L-GPIO_BASE))); out_be32((gpio_base+(GPIO0_ISR2L-GPIO_BASE)), val & gpio_mask); /* ISR3L */ val = in_be32((gpio_base+(GPIO0_ISR3L-GPIO_BASE))); out_be32((gpio_base+(GPIO0_ISR3L-GPIO_BASE)), val & gpio_mask); } else { /* OSRH: b2n,b2n+1 <= '00' select GPIO0_OR */ val = in_be32((gpio_base+(GPIO0_OSRH-GPIO_BASE))); out_be32((gpio_base+(GPIO0_OSRH-GPIO_BASE)), val & gpio_mask); /* TSRH: b2n,b2n+1 <= '00' select TCR */ val = in_be32((gpio_base+(GPIO0_TSRH-GPIO_BASE))); out_be32((gpio_base+(GPIO0_TSRH-GPIO_BASE)), val & gpio_mask); /* ISR1H */ val = in_be32((gpio_base+(GPIO0_ISR1H-GPIO_BASE))); out_be32((gpio_base+(GPIO0_ISR1H-GPIO_BASE)), val & gpio_mask); /* ISR2H */ val = in_be32((gpio_base+(GPIO0_ISR2H-GPIO_BASE))); out_be32((gpio_base+(GPIO0_ISR2H-GPIO_BASE)), val & gpio_mask); /* ISR3H */ val = in_be32((gpio_base+(GPIO0_ISR3H-GPIO_BASE))); out_be32((gpio_base+(GPIO0_ISR3H-GPIO_BASE)), val & gpio_mask); } } } bool safenet_linux_gpio_init(void) { if (!gpio_base) { printk(KERN_INFO "Safenet linux gpio: INITIALIZING...\n"); if ((gpio_base = ioremap_nocache(GPIO_BASE, 0x100)) == NULL) { printk(KERN_INFO "Safenet linux gpio: can't get" \ " remap phys address 0x%lx\n",GPIO_BASE); return false; } } /* initializing our debug gpio lines: */ safenet_linux_gpio_out_hard(4, false); safenet_linux_gpio_out_hard(5, false); safenet_linux_gpio_out_hard(6, false); safenet_linux_gpio_out_hard(7, false); safenet_linux_gpio_out_hard(12, false); safenet_linux_gpio_out_hard(13, false); safenet_linux_gpio_out_hard(14, false); safenet_linux_gpio_out_hard(15, false); return true; } void safenet_linux_gpio_uninit(void) { if (gpio_base) { printk(KERN_INFO "Safenet linux gpio: CLEANING UP...\n"); iounmap((void __iomem *)gpio_base); /* release_mem_region(gpio_base, 0x100); */ gpio_base = NULL; } } #else /* SAFENET_DEBUG_USE_GPIO */ #define safenet_linux_gpio_init() 1==1 #define safenet_linux_gpio_out_high(gpio_sig_num) do {} while (0) #define safenet_linux_gpio_out_low(gpio_sig_num) do {} while (0) #define safenet_linux_gpio_out_hard(gpio_sig_num, high) do {} while (0) #define safenet_linux_gpio_uninit() do {} while (0) #endif /* SAFENET_DEBUG_USE_GPIO */ #endif /* SAFENET_405EX_GPIO_H */
30.254032
79
0.664268
ce1adafaa560c5de45aed7913ed67bd44942515a
10,418
c
C
release/src/linux/linux/drivers/net/wan/cycx_main.c
enfoTek/tomato.linksys.e2000.nvram-mod
2ce3a5217def49d6df7348522e2bfda702b56029
[ "FSFAP" ]
278
2015-11-03T03:01:20.000Z
2022-01-20T18:21:05.000Z
release/src/linux/linux/drivers/net/wan/cycx_main.c
unforgiven512/tomato
96f09fab4929c6ddde5c9113f1b2476ad37133c4
[ "FSFAP" ]
374
2015-11-03T12:37:22.000Z
2021-12-17T14:18:08.000Z
release/src/linux/linux/drivers/net/wan/cycx_main.c
unforgiven512/tomato
96f09fab4929c6ddde5c9113f1b2476ad37133c4
[ "FSFAP" ]
96
2015-11-22T07:47:26.000Z
2022-01-20T19:52:19.000Z
/* * cycx_main.c Cyclades Cyclom 2X WAN Link Driver. Main module. * * Author: Arnaldo Carvalho de Melo <acme@conectiva.com.br> * * Copyright: (c) 1998-2001 Arnaldo Carvalho de Melo * * Based on sdlamain.c by Gene Kozin <genek@compuserve.com> & * Jaspreet Singh <jaspreet@sangoma.com> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * ============================================================================ * 2001/05/09 acme Fix MODULE_DESC for debug, .bss nitpicks, * some cleanups * 2000/07/13 acme remove useless #ifdef MODULE and crap * #if KERNEL_VERSION > blah * 2000/07/06 acme __exit at cyclomx_cleanup * 2000/04/02 acme dprintk and cycx_debug * module_init/module_exit * 2000/01/21 acme rename cyclomx_open to cyclomx_mod_inc_use_count * and cyclomx_close to cyclomx_mod_dec_use_count * 2000/01/08 acme cleanup * 1999/11/06 acme cycx_down back to life (it needs to be * called to iounmap the dpmbase) * 1999/08/09 acme removed references to enable_tx_int * use spinlocks instead of cli/sti in * cyclomx_set_state * 1999/05/19 acme works directly linked into the kernel * init_waitqueue_head for 2.3.* kernel * 1999/05/18 acme major cleanup (polling not needed), etc * 1998/08/28 acme minor cleanup (ioctls for firmware deleted) * queue_task activated * 1998/08/08 acme Initial version. */ #include <linux/config.h> /* OS configuration options */ #include <linux/stddef.h> /* offsetof(), etc. */ #include <linux/errno.h> /* return codes */ #include <linux/string.h> /* inline memset(), etc. */ #include <linux/slab.h> /* kmalloc(), kfree() */ #include <linux/kernel.h> /* printk(), and other useful stuff */ #include <linux/module.h> /* support for loadable modules */ #include <linux/ioport.h> /* request_region(), release_region() */ #include <linux/tqueue.h> /* for kernel task queues */ #include <linux/wanrouter.h> /* WAN router definitions */ #include <linux/cyclomx.h> /* cyclomx common user API definitions */ #include <asm/uaccess.h> /* kernel <-> user copy */ #include <linux/init.h> /* __init (when not using as a module) */ /* Debug */ unsigned int cycx_debug; MODULE_AUTHOR("Arnaldo Carvalho de Melo"); MODULE_DESCRIPTION("Cyclom 2X Sync Card Driver."); MODULE_LICENSE("GPL"); MODULE_PARM(cycx_debug, "i"); MODULE_PARM_DESC(cycx_debug, "cyclomx debug level"); /* Defines & Macros */ #define DRV_VERSION 0 /* version number */ #define DRV_RELEASE 10 /* release (minor version) number */ #define MAX_CARDS 1 /* max number of adapters */ #define CONFIG_CYCLOMX_CARDS 1 /* Function Prototypes */ /* WAN link driver entry points */ static int setup (wan_device_t *wandev, wandev_conf_t *conf); static int shutdown (wan_device_t *wandev); static int ioctl (wan_device_t *wandev, unsigned cmd, unsigned long arg); /* Miscellaneous functions */ static void cycx_isr (int irq, void *dev_id, struct pt_regs *regs); /* Global Data * Note: All data must be explicitly initialized!!! */ /* private data */ static char drvname[] = "cyclomx"; static char fullname[] = "CYCLOM 2X(tm) Sync Card Driver"; static char copyright[] = "(c) 1998-2001 Arnaldo Carvalho de Melo " "<acme@conectiva.com.br>"; static int ncards = CONFIG_CYCLOMX_CARDS; static cycx_t *card_array; /* adapter data space */ /* Kernel Loadable Module Entry Points */ /* * Module 'insert' entry point. * o print announcement * o allocate adapter data space * o initialize static data * o register all cards with WAN router * o calibrate Cyclom 2X shared memory access delay. * * Return: 0 Ok * < 0 error. * Context: process */ int __init cyclomx_init (void) { int cnt, err = -ENOMEM; printk(KERN_INFO "%s v%u.%u %s\n", fullname, DRV_VERSION, DRV_RELEASE, copyright); /* Verify number of cards and allocate adapter data space */ ncards = min_t(int, ncards, MAX_CARDS); ncards = max_t(int, ncards, 1); card_array = kmalloc(sizeof(cycx_t) * ncards, GFP_KERNEL); if (!card_array) goto out; memset(card_array, 0, sizeof(cycx_t) * ncards); /* Register adapters with WAN router */ for (cnt = 0; cnt < ncards; ++cnt) { cycx_t *card = &card_array[cnt]; wan_device_t *wandev = &card->wandev; sprintf(card->devname, "%s%d", drvname, cnt + 1); wandev->magic = ROUTER_MAGIC; wandev->name = card->devname; wandev->private = card; wandev->setup = setup; wandev->shutdown = shutdown; wandev->ioctl = ioctl; err = register_wan_device(wandev); if (err) { printk(KERN_ERR "%s: %s registration failed with " "error %d!\n", drvname, card->devname, err); break; } } err = -ENODEV; if (!cnt) { kfree(card_array); goto out; } err = 0; ncards = cnt; /* adjust actual number of cards */ out: return err; } /* * Module 'remove' entry point. * o unregister all adapters from the WAN router * o release all remaining system resources */ static void __exit cyclomx_cleanup (void) { int i = 0; for (; i < ncards; ++i) { cycx_t *card = &card_array[i]; unregister_wan_device(card->devname); } kfree(card_array); } /* WAN Device Driver Entry Points */ /* * Setup/configure WAN link driver. * o check adapter state * o make sure firmware is present in configuration * o allocate interrupt vector * o setup Cyclom 2X hardware * o call appropriate routine to perform protocol-specific initialization * * This function is called when router handles ROUTER_SETUP IOCTL. The * configuration structure is in kernel memory (including extended data, if * any). */ static int setup (wan_device_t *wandev, wandev_conf_t *conf) { int err = -EFAULT; cycx_t *card; int irq; /* Sanity checks */ if (!wandev || !wandev->private || !conf) goto out; card = wandev->private; err = -EBUSY; if (wandev->state != WAN_UNCONFIGURED) goto out; err = -EINVAL; if (!conf->data_size || !conf->data) { printk(KERN_ERR "%s: firmware not found in configuration " "data!\n", wandev->name); goto out; } if (conf->irq <= 0) { printk(KERN_ERR "%s: can't configure without IRQ!\n", wandev->name); goto out; } /* Allocate IRQ */ irq = conf->irq == 2 ? 9 : conf->irq; /* IRQ2 -> IRQ9 */ if (request_irq(irq, cycx_isr, 0, wandev->name, card)) { printk(KERN_ERR "%s: can't reserve IRQ %d!\n", wandev->name, irq); goto out; } /* Configure hardware, load firmware, etc. */ memset(&card->hw, 0, sizeof(cycxhw_t)); card->hw.irq = irq; card->hw.dpmbase = conf->maddr; card->hw.dpmsize = CYCX_WINDOWSIZE; card->hw.fwid = CFID_X25_2X; card->lock = SPIN_LOCK_UNLOCKED; init_waitqueue_head(&card->wait_stats); err = cycx_setup(&card->hw, conf->data, conf->data_size); if (err) goto out_irq; /* Initialize WAN device data space */ wandev->irq = irq; wandev->dma = wandev->ioport = 0; wandev->maddr = card->hw.dpmbase; wandev->msize = card->hw.dpmsize; wandev->hw_opt[2] = 0; wandev->hw_opt[3] = card->hw.fwid; /* Protocol-specific initialization */ switch (card->hw.fwid) { #ifdef CONFIG_CYCLOMX_X25 case CFID_X25_2X: err = cyx_init(card, conf); break; #endif default: printk(KERN_ERR "%s: this firmware is not supported!\n", wandev->name); err = -EINVAL; } if (err) { cycx_down(&card->hw); goto out_irq; } err = 0; out: return err; out_irq: free_irq(irq, card); goto out; } /* * Shut down WAN link driver. * o shut down adapter hardware * o release system resources. * * This function is called by the router when device is being unregistered or * when it handles ROUTER_DOWN IOCTL. */ static int shutdown (wan_device_t *wandev) { int ret = -EFAULT; cycx_t *card; /* sanity checks */ if (!wandev || !wandev->private) goto out; ret = 0; if (wandev->state == WAN_UNCONFIGURED) goto out; card = wandev->private; wandev->state = WAN_UNCONFIGURED; cycx_down(&card->hw); printk(KERN_INFO "%s: irq %d being freed!\n", wandev->name, wandev->irq); free_irq(wandev->irq, card); out: return ret; } /* * Driver I/O control. * o verify arguments * o perform requested action * * This function is called when router handles one of the reserved user * IOCTLs. Note that 'arg' still points to user address space. * * no reserved ioctls for the cyclom 2x up to now */ static int ioctl (wan_device_t *wandev, unsigned cmd, unsigned long arg) { return -EINVAL; } /* Miscellaneous */ /* * Cyclom 2X Interrupt Service Routine. * o acknowledge Cyclom 2X hardware interrupt. * o call protocol-specific interrupt service routine, if any. */ static void cycx_isr (int irq, void *dev_id, struct pt_regs *regs) { cycx_t *card = (cycx_t *)dev_id; if (!card || card->wandev.state == WAN_UNCONFIGURED) goto out; if (card->in_isr) { printk(KERN_WARNING "%s: interrupt re-entrancy on IRQ %d!\n", card->devname, card->wandev.irq); goto out; } if (card->isr) card->isr(card); out: return; } /* * This routine is called by the protocol-specific modules when network * interface is being open. The only reason we need this, is because we * have to call MOD_INC_USE_COUNT, but cannot include 'module.h' where it's * defined more than once into the same kernel module. */ void cyclomx_mod_inc_use_count (cycx_t *card) { ++card->open_cnt; MOD_INC_USE_COUNT; } /* * This routine is called by the protocol-specific modules when network * interface is being closed. The only reason we need this, is because we * have to call MOD_DEC_USE_COUNT, but cannot include 'module.h' where it's * defined more than once into the same kernel module. */ void cyclomx_mod_dec_use_count (cycx_t *card) { --card->open_cnt; MOD_DEC_USE_COUNT; } /* Set WAN device state. */ void cyclomx_set_state (cycx_t *card, int state) { unsigned long flags; char *string_state = NULL; spin_lock_irqsave(&card->lock, flags); if (card->wandev.state != state) { switch (state) { case WAN_CONNECTED: string_state = "connected!"; break; case WAN_DISCONNECTED: string_state = "disconnected!"; break; } printk(KERN_INFO "%s: link %s\n", card->devname, string_state); card->wandev.state = state; } card->state_tick = jiffies; spin_unlock_irqrestore(&card->lock, flags); } module_init(cyclomx_init); module_exit(cyclomx_cleanup);
26.644501
78
0.685352
ce8d3eb51a6d7a3d2adfc7008df268694196bb0f
12,746
c
C
rtos/libwwg/src/uartlib.c
iMorphiy/stm32
4a50098e9d5ff6cec3820c147de557b963544c72
[ "MIT" ]
null
null
null
rtos/libwwg/src/uartlib.c
iMorphiy/stm32
4a50098e9d5ff6cec3820c147de557b963544c72
[ "MIT" ]
null
null
null
rtos/libwwg/src/uartlib.c
iMorphiy/stm32
4a50098e9d5ff6cec3820c147de557b963544c72
[ "MIT" ]
null
null
null
/* Interrupt driven USART Library * Warren W. Gay VE3WWG Tue Feb 21 20:35:54 2017 */ #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <FreeRTOS.h> #include <task.h> #include <queue.h> #include <libopencm3/stm32/rcc.h> #include <libopencm3/stm32/gpio.h> #include <libopencm3/stm32/usart.h> #include <libopencm3/cm3/nvic.h> #include <uartlib.h> #include <miniprintf.h> #include <getline.h> /********************************************************************* * Receive buffers *********************************************************************/ #define USART_BUF_DEPTH 32 struct s_uart { volatile uint16_t head; /* Buffer head index (pop) */ volatile uint16_t tail; /* Buffer tail index (push) */ uint8_t buf[USART_BUF_DEPTH]; /* Circular receive buffer */ }; struct s_uart_info { uint32_t usart; /* USART address */ uint32_t rcc; /* RCC address */ uint32_t irq; /* IRQ number */ int (*getc)(void); void (*putc)(char ch); }; static struct s_uart_info uarts[3] = { { USART1, RCC_USART1, NVIC_USART1_IRQ, uart1_getc, uart1_putc }, { USART2, RCC_USART2, NVIC_USART2_IRQ, uart2_getc, uart2_putc }, { USART3, RCC_USART3, NVIC_USART3_IRQ, uart3_getc, uart3_putc } }; static struct s_uart *uart_data[3] = { 0, 0, 0 }; /********************************************************************* * Receive data for USART *********************************************************************/ static void uart_common_isr(unsigned ux) { struct s_uart *uartp = uart_data[ux]; /* Access USART's buffer */ uint32_t uart = uarts[ux].usart; /* Lookup USART address */ uint32_t ntail; /* Next tail index */ char ch; /* Read data byte */ if ( !uartp ) return; /* Not open for ISR receiving! */ while ( USART_SR(uart) & USART_SR_RXNE ) { /* Read status */ ch = USART_DR(uart); /* Read data */ ntail = (uartp->tail + 1) % USART_BUF_DEPTH; /* Calc next tail index */ /* Save data if the buffer is not full */ if ( ntail != uartp->head ) { /* Not full? */ uartp->buf[uartp->tail] = ch; /* No, stow into buffer */ uartp->tail = ntail; /* Advance tail index */ } } } /********************************************************************* * USART1 ISR *********************************************************************/ void usart1_isr(void) { uart_common_isr(0); } /********************************************************************* * USART2 ISR *********************************************************************/ void usart2_isr(void) { uart_common_isr(1); } /********************************************************************* * USART3 ISR *********************************************************************/ void usart3_isr(void) { uart_common_isr(2); } /********************************************************************* * Open the UART for I/O: * * ARGUMENTS: * 1. uartno 1 == USART1, ... 3 == USART3 * 2. baud Baud rate, eg. 38400 * 3. cfg Config: eg. "8N1" * 4. mode "r", "rw" or just "w" * 5. rts When True: Use RTS * 6. cts When True: Use CTS * * RETURNS: * 0 Success * -1 Fail: Bad uartno * -2 Fail: Bad parity config * -3 Fail: Bad mode config (r/w) * -4 Fail: Bad stop bits config * * EXAMPLES: * open_uart(1,38400,"8N1","w",0,0); UART1, TX, No RTS/CTS * open_uart(2,19200,"7E1","rw",0,0); UART2, RX+TX, No RTS/CTS * open_uart(3,115200,"8N1","rw",1,1); UART3, RX+TX, RTS/CTS *********************************************************************/ int open_uart(uint32_t uartno,uint32_t baud,const char *cfg,const char *mode,int rts,int cts) { uint32_t uart, ux, stopb, iomode, parity, fc; struct s_uart_info *infop; bool rxintf = false; if ( uartno < 1 || uartno > 3 ) return -1; /* Invalid UART ref */ infop = &uarts[ux = uartno-1]; /* USART parameters */ uart = infop->usart; /* USART address */ usart_disable_rx_interrupt(uart); /************************************************************* * Parity *************************************************************/ switch ( cfg[1] ) { case 'O': parity = USART_PARITY_ODD; break; case 'E': parity = USART_PARITY_EVEN; break; case 'N': parity = USART_PARITY_NONE; break; /* No Mark parity? Use 2-stop bits for that? */ default: return -2; // Bad parity } /************************************************************* * Stop bits *************************************************************/ stopb = USART_STOPBITS_1; switch ( cfg[2] ) { case '.': case '0': stopb = USART_STOPBITS_0_5; break; case '1': if ( cfg[3] == '.' ) stopb = USART_STOPBITS_1_5; else stopb = USART_STOPBITS_1; break; case '2': stopb = USART_STOPBITS_2; break; default: return -4; } /************************************************************* * Transmit mode: "r", "w" or "rw" *************************************************************/ if ( mode[0] == 'r' && mode[1] == 'w' ) { iomode = USART_MODE_TX_RX; rxintf = true; } else if ( mode[0] == 'r' ) { iomode = USART_MODE_RX; rxintf = true; } else if ( mode[0] == 'w' ) iomode = USART_MODE_TX; else return -3; /* Mode fail */ /************************************************************* * Setup RX ISR *************************************************************/ if ( rxintf ) { if ( uart_data[ux] == 0 ) uart_data[ux] = malloc(sizeof(struct s_uart)); uart_data[ux]->head = uart_data[ux]->tail = 0; } /************************************************************* * Flow control mode: *************************************************************/ fc = USART_FLOWCONTROL_NONE; if ( rts ) { if ( cts ) fc = USART_FLOWCONTROL_RTS_CTS; else fc = USART_FLOWCONTROL_RTS; } else if ( cts ) { fc = USART_FLOWCONTROL_CTS; } /************************************************************* * Establish settings: *************************************************************/ rcc_periph_clock_enable(infop->rcc); usart_set_baudrate(uart,baud); usart_set_databits(uart,cfg[0]&0x0F); usart_set_stopbits(uart,stopb); usart_set_mode(uart,iomode); usart_set_parity(uart,parity); usart_set_flow_control(uart,fc); nvic_enable_irq(infop->irq); usart_enable(uart); usart_enable_rx_interrupt(uart); return 0; /* Success */ } /********************************************************************* * Put one character to device, non-blocking * * RETURNS: * 0 Sent char * -1 Device busy *********************************************************************/ int putc_uart_nb(uint32_t uartno,char ch) { uint32_t uart = uarts[uartno-1].usart; if ( (USART_SR(uart) & USART_SR_TXE) == 0 ) return -1; /* Busy */ usart_send_blocking(uart,ch); return 0; /* Success */ } /********************************************************************* * Put one character to device, block (yield) until TX ready (blocking) *********************************************************************/ void putc_uart(uint32_t uartno,char ch) { uint32_t uart = uarts[uartno-1].usart; while ( (USART_SR(uart) & USART_SR_TXE) == 0 ) taskYIELD(); usart_send_blocking(uart,ch); } /********************************************************************* * Write size bytes to TX, yielding until all is sent (blocking) *********************************************************************/ void write_uart(uint32_t uartno,const char *buf,uint32_t size) { uint32_t uart = uarts[uartno-1].usart; for ( ; size > 0; --size ) { while ( (USART_SR(uart) & USART_SR_TXE) == 0 ) taskYIELD(); usart_send_blocking(uart,*buf++); } } /********************************************************************* * Send Null terminated string, yeilding (blocking) *********************************************************************/ void puts_uart(uint32_t uartno,const char *buf) { uint32_t uart = uarts[uartno-1].usart; while ( *buf ) { while ( (USART_SR(uart) & USART_SR_TXE) == 0 ) taskYIELD(); usart_send_blocking(uart,*buf++); } } /********************************************************************* * Internal: Return data given s_uart * *********************************************************************/ static int get_char(struct s_uart *uptr) { char rch; if ( uptr->head == uptr->tail ) return -1; // No data available rch = uptr->buf[uptr->head]; uptr->head = ( uptr->head + 1 ) % USART_BUF_DEPTH; return rch; } /********************************************************************* * Receive a byte, non-blocking *********************************************************************/ int getc_uart_nb(uint32_t uartno) { struct s_uart *uptr = uart_data[uartno-1]; if ( !uptr ) return -1; // No known uart return get_char(uptr); } /********************************************************************* * Receive a byte, blocking *********************************************************************/ char getc_uart(uint32_t uartno) { struct s_uart *uptr = uart_data[uartno-1]; int rch; if ( !uptr ) return -1; // No known uart while ( (rch = get_char(uptr)) == -1 ) taskYIELD(); return (char)rch; } /********************************************************************* * Get cooked input line *********************************************************************/ int getline_uart(uint32_t uartno,char *buf,uint32_t bufsiz) { struct s_uart_info *uart = &uarts[uartno-1]; return getline(buf,bufsiz,uart->getc,uart->putc); } /********************************************************************* * Close USART (frees RAM) *********************************************************************/ void close_uart(uint32_t uartno) { uint32_t ux = uartno - 1; struct s_uart *uptr = uart_data[ux]; usart_disable_rx_interrupt(uarts[ux].usart); if ( uptr && uart_data[ux] ) { free(uart_data[ux]); uart_data[ux] = 0; } } /********************************************************************* * Optional use routines for UART1 *********************************************************************/ void uart1_putc(char ch) { if ( ch == '\n' ) putc_uart(1,'\r'); putc_uart(1,ch); } void uart1_puts(const char *buf) { puts_uart(1,buf); } int uart1_vprintf(const char *format,va_list ap) { return mini_vprintf_cooked(uart1_putc,format,ap); } int uart1_printf(const char *format,...) { va_list args; int rc; va_start(args,format); rc = mini_vprintf_cooked(uart1_putc,format,args); va_end(args); return rc; } int uart1_getc(void) { return getc_uart(1); } int uart1_peek(void) { return getc_uart_nb(1); } int uart1_gets(char *buf,unsigned bufsiz) { return getline_uart(1,buf,bufsiz); } void uart1_write(const char *buf,unsigned bytes) { write_uart(1,buf,bytes); } int uart1_getline(char *buf,unsigned bufsiz) { return getline_uart(1,buf,bufsiz); } /********************************************************************* * Optional use routines for UART2 *********************************************************************/ void uart2_putc(char ch) { if ( ch == '\n' ) putc_uart(2,'\r'); putc_uart(2,ch); } void uart2_puts(const char *buf) { puts_uart(2,buf); } int uart2_vprintf(const char *format,va_list ap) { return mini_vprintf_cooked(uart2_putc,format,ap); } int uart2_printf(const char *format,...) { va_list args; int rc; va_start(args,format); rc = mini_vprintf_cooked(uart2_putc,format,args); va_end(args); return rc; } int uart2_getc(void) { return getc_uart(2); } int uart2_peek(void) { return getc_uart_nb(2); } int uart2_gets(char *buf,unsigned bufsiz) { return getline_uart(2,buf,bufsiz); } void uart2_write(const char *buf,unsigned bytes) { write_uart(2,buf,bytes); } int uart2_getline(char *buf,unsigned bufsiz) { return getline_uart(2,buf,bufsiz); } /********************************************************************* * Optional use routines for UART3 *********************************************************************/ void uart3_putc(char ch) { if ( ch == '\n' ) putc_uart(3,'\r'); putc_uart(3,ch); } void uart3_puts(const char *buf) { puts_uart(3,buf); } int uart3_vprintf(const char *format,va_list ap) { return mini_vprintf_cooked(uart3_putc,format,ap); } int uart3_printf(const char *format,...) { va_list args; int rc; va_start(args,format); rc = mini_vprintf_cooked(uart3_putc,format,args); va_end(args); return rc; } int uart3_getc(void) { return getc_uart(3); } int uart3_peek(void) { return getc_uart_nb(3); } int uart3_gets(char *buf,unsigned bufsiz) { return getline_uart(3,buf,bufsiz); } int uart3_getline(char *buf,unsigned bufsiz) { return getline_uart(3,buf,bufsiz); } void uart3_write(const char *buf,unsigned bytes) { write_uart(3,buf,bytes); } /* End uartlib.c */
23.603704
91
0.492311
07a4732445101c4f8693d0cb255bde5751273b87
2,345
c
C
build/third_party/libzip/lib/zip_file_set_comment.c
HopeBayMobile/hcfs
153666610f42fd6c39f2ca1f1864ebb8652e6b2c
[ "Apache-2.0" ]
null
null
null
build/third_party/libzip/lib/zip_file_set_comment.c
HopeBayMobile/hcfs
153666610f42fd6c39f2ca1f1864ebb8652e6b2c
[ "Apache-2.0" ]
null
null
null
build/third_party/libzip/lib/zip_file_set_comment.c
HopeBayMobile/hcfs
153666610f42fd6c39f2ca1f1864ebb8652e6b2c
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2021 HopeBayTech. * * This file is part of Tera. * See https://github.com/HopeBayMobile for further info. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <stdlib.h> #include "zipint.h" ZIP_EXTERN int zip_file_set_comment(zip_t *za, zip_uint64_t idx, const char *comment, zip_uint16_t len, zip_flags_t flags) { zip_entry_t *e; zip_string_t *cstr; int changed; if (_zip_get_dirent(za, idx, 0, NULL) == NULL) return -1; if (ZIP_IS_RDONLY(za)) { zip_error_set(&za->error, ZIP_ER_RDONLY, 0); return -1; } if (len > 0 && comment == NULL) { zip_error_set(&za->error, ZIP_ER_INVAL, 0); return -1; } if (len > 0) { if ((cstr=_zip_string_new((const zip_uint8_t *)comment, len, flags, &za->error)) == NULL) return -1; if ((flags & ZIP_FL_ENCODING_ALL) == ZIP_FL_ENC_GUESS && _zip_guess_encoding(cstr, ZIP_ENCODING_UNKNOWN) == ZIP_ENCODING_UTF8_GUESSED) cstr->encoding = ZIP_ENCODING_UTF8_KNOWN; } else cstr = NULL; e = za->entry+idx; if (e->changes) { _zip_string_free(e->changes->comment); e->changes->comment = NULL; e->changes->changed &= ~ZIP_DIRENT_COMMENT; } if (e->orig && e->orig->comment) changed = !_zip_string_equal(e->orig->comment, cstr); else changed = (cstr != NULL); if (changed) { if (e->changes == NULL) { if ((e->changes=_zip_dirent_clone(e->orig)) == NULL) { zip_error_set(&za->error, ZIP_ER_MEMORY, 0); _zip_string_free(cstr); return -1; } } e->changes->comment = cstr; e->changes->changed |= ZIP_DIRENT_COMMENT; } else { _zip_string_free(cstr); if (e->changes && e->changes->changed == 0) { _zip_dirent_free(e->changes); e->changes = NULL; } } return 0; }
26.055556
135
0.642217
6d73809815452b091f1a61fca08b4908484bd32b
5,384
h
C
Source Code/Graphs/Headers/Octree.h
IonutCava/trunk
19dc976bbd7dc637f467785bd0ca15f34bc31ed5
[ "MIT" ]
null
null
null
Source Code/Graphs/Headers/Octree.h
IonutCava/trunk
19dc976bbd7dc637f467785bd0ca15f34bc31ed5
[ "MIT" ]
null
null
null
Source Code/Graphs/Headers/Octree.h
IonutCava/trunk
19dc976bbd7dc637f467785bd0ca15f34bc31ed5
[ "MIT" ]
null
null
null
/* Copyright (c) 2018 DIVIDE-Studio Copyright (c) 2009 Ionut Cava This file is part of DIVIDE Framework. 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. */ #pragma once #ifndef _OCTREE_H_ #define _OCTREE_H_ #include "IntersectionRecord.h" #include "Core/Math/BoundingVolumes/Headers/BoundingBox.h" namespace Divide { class Frustum; class SceneGraphNode; class BoundsComponent; struct SGNIntersectionParams; // ref: http://www.gamedev.net/page/resources/_/technical/game-programming/introduction-to-octrees-r3529 class Octree { public: explicit Octree(U16 nodeMask); void update(U64 deltaTimeUS); [[nodiscard]] bool addNode(SceneGraphNode* node); [[nodiscard]] bool removeNode(SceneGraphNode* node); [[nodiscard]] vector<IntersectionRecord> allIntersections(const Frustum& region, U16 typeFilterMask); [[nodiscard]] vector<IntersectionRecord> allIntersections(const Ray& intersectionRay, F32 start, F32 end); [[nodiscard]] vector<IntersectionRecord> allIntersections(const Ray& intersectionRay, F32 start, F32 end, U16 typeFilterMask); [[nodiscard]] IntersectionRecord nearestIntersection(const Ray& intersectionRay, F32 start, F32 end, U16 typeFilterMask); void getAllRegions(vector<BoundingBox>& regionsOut) const; protected: friend class SceneGraph; void onNodeMoved(const SceneGraphNode& sgn); protected: friend class OctreeNode; void onChildBuildTree(); void onChildStateChange(OctreeNode* node, bool state); private: void updateTree(); void handleIntersection(const IntersectionRecord& intersection) const; protected: eastl::unique_ptr<OctreeNode> _root = nullptr; vector<const SceneGraphNode*> _intersectionsObjectCache; eastl::queue<SceneGraphNode*> _pendingInsertion; eastl::queue<SceneGraphNode*> _pendingRemoval; Mutex _pendingInsertLock; bool _treeReady = false; bool _treeBuilt = false; const U16 _nodeExclusionMask = 0u; Mutex _linearObjectCacheLock; vector<OctreeNode*> _linearObjectCache; }; class OctreeNode { public: /// Minimum cube size is 1x1x1 static constexpr F32 MIN_SIZE = 1.0f; static constexpr I32 MAX_LIFE_SPAN_LIMIT = 64; explicit OctreeNode(OctreeNode* parent, U16 nodeMask, Octree* parentTree); void update(U64 deltaTimeUS); void getAllRegions(vector<BoundingBox>& regionsOut) const; [[nodiscard]] const BoundingBox& getRegion() const noexcept { return _region; } protected: friend class Octree; [[nodiscard]] U8 activeNodes() const noexcept; void buildTree(); void insert(const SceneGraphNode* object); void findEnclosingBox(); void findEnclosingCube(); [[nodiscard]] vector<IntersectionRecord> getIntersection(const Frustum& frustum, U16 typeFilterMask) const; [[nodiscard]] vector<IntersectionRecord> getIntersection(const Ray& intersectRay, F32 start, F32 end, U16 typeFilterMask) const; [[nodiscard]] size_t getTotalObjectCount() const; void updateIntersectionCache(vector<const SceneGraphNode*>& parentObjects); [[nodiscard]] bool getIntersection(BoundsComponent* bComp, const Frustum& frustum, IntersectionRecord& irOut) const noexcept; [[nodiscard]] bool getIntersection(BoundsComponent* bComp1, BoundsComponent* bComp2, IntersectionRecord& irOut) const noexcept; [[nodiscard]] bool getIntersection(BoundsComponent* bComp, const Ray& intersectRay, F32 start, F32 end, IntersectionRecord& irOut) const noexcept; PROPERTY_R_IW(bool, active, false); private: Octree* const _parentTree = nullptr; OctreeNode* const _parent = nullptr; const U16 _nodeExclusionMask = 0u; mutable SharedMutex _objectLock; eastl::fixed_vector<const SceneGraphNode*, 8, true, eastl::dvd_allocator> _objects; moodycamel::ConcurrentQueue<const SceneGraphNode*> _movedObjects; vector<IntersectionRecord> _intersectionsCache; BoundingBox _region; I32 _curLife = -1; I32 _maxLifespan = MAX_LIFE_SPAN_LIMIT / 8; std::array<eastl::unique_ptr<OctreeNode>, 8> _childNodes; //ToDo: make this work in a multi-threaded environment mutable I8 _frustPlaneCache = -1; }; }; // namespace Divide #endif
36.134228
151
0.730498
7713f89e6df6a66dfedf919b9ec0d7d505af31f9
39,894
c
C
RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/src/service.c
nicklela/edk2
dfafa8e45382939fb5dc78e9d37b97b500a43613
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "BSD-2-Clause-Patent", "BSD-3-Clause" ]
31
2019-05-14T09:00:56.000Z
2022-03-16T12:36:49.000Z
RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/src/service.c
nicklela/edk2
dfafa8e45382939fb5dc78e9d37b97b500a43613
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "BSD-2-Clause-Patent", "BSD-3-Clause" ]
21
2020-03-09T18:54:14.000Z
2022-01-01T00:30:53.000Z
RedfishPkg/PrivateLibrary/RedfishLib/edk2libredfish/src/service.c
nicklela/edk2
dfafa8e45382939fb5dc78e9d37b97b500a43613
[ "Python-2.0", "Zlib", "BSD-2-Clause", "MIT", "BSD-2-Clause-Patent", "BSD-3-Clause" ]
25
2018-09-05T02:46:06.000Z
2022-03-20T18:58:40.000Z
/** @file This file is cloned from DMTF libredfish library tag v1.0.0 and maintained by EDKII. //---------------------------------------------------------------------------- // Copyright Notice: // Copyright 2017 Distributed Management Task Force, Inc. All rights reserved. // License: BSD 3-Clause License. For full text see link: https://github.com/DMTF/libredfish/LICENSE.md //---------------------------------------------------------------------------- Copyright (c) 2019, Intel Corporation. All rights reserved.<BR> (C) Copyright 2021 Hewlett Packard Enterprise Development LP<BR> SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include <redfishService.h> #include <redfishPayload.h> #include <redpath.h> static int initRest(redfishService* service, void * restProtocol); static redfishService* createServiceEnumeratorNoAuth(const char* host, const char* rootUri, bool enumerate, unsigned int flags, void * restProtocol); static redfishService* createServiceEnumeratorBasicAuth(const char* host, const char* rootUri, const char* username, const char* password, unsigned int flags, void * restProtocol); static redfishService* createServiceEnumeratorSessionAuth(const char* host, const char* rootUri, const char* username, const char* password, unsigned int flags, void * restProtocol); static char* makeUrlForService(redfishService* service, const char* uri); static json_t* getVersions(redfishService* service, const char* rootUri); static void addStringToJsonObject(json_t* object, const char* key, const char* value); CHAR16* C8ToC16 (CHAR8 *AsciiStr) { CHAR16 *Str; UINTN BufLen; BufLen = (AsciiStrLen (AsciiStr) + 1) * 2; Str = AllocatePool (BufLen); ASSERT (Str != NULL); AsciiStrToUnicodeStrS (AsciiStr, Str, AsciiStrLen (AsciiStr) + 1); return Str; } VOID RestConfigFreeHttpRequestData ( IN EFI_HTTP_REQUEST_DATA *RequestData ) { if (RequestData == NULL) { return ; } if (RequestData->Url != NULL) { FreePool (RequestData->Url); } FreePool (RequestData); } VOID RestConfigFreeHttpMessage ( IN EFI_HTTP_MESSAGE *Message, IN BOOLEAN IsRequest ) { if (Message == NULL) { return ; } if (IsRequest) { RestConfigFreeHttpRequestData (Message->Data.Request); Message->Data.Request = NULL; } else { if (Message->Data.Response != NULL) { FreePool (Message->Data.Response); Message->Data.Response = NULL; } } if (Message->Headers != NULL) { FreePool (Message->Headers); Message->Headers = NULL; } if (Message->Body != NULL) { FreePool (Message->Body); Message->Body = NULL; } } /** Converts the Unicode string to ASCII string to a new allocated buffer. @param[in] String Unicode string to be converted. @return Buffer points to ASCII string, or NULL if error happens. **/ CHAR8 * UnicodeStrDupToAsciiStr ( CONST CHAR16 *String ) { CHAR8 *AsciiStr; UINTN BufLen; EFI_STATUS Status; BufLen = StrLen (String) + 1; AsciiStr = AllocatePool (BufLen); if (AsciiStr == NULL) { return NULL; } Status = UnicodeStrToAsciiStrS (String, AsciiStr, BufLen); if (EFI_ERROR (Status)) { return NULL; } return AsciiStr; } /** This function encodes the content. @param[in] ContentEncodedValue HTTP conent encoded value. @param[in] OriginalContent Original content. @param[out] EncodedContent Pointer to receive encoded content. @param[out] EncodedContentLength Length of encoded content. @retval EFI_SUCCESS Content encoded successfully. @retval EFI_UNSUPPORTED No source encoding funciton, @retval EFI_INVALID_PARAMETER One of the given parameter is invalid. **/ EFI_STATUS EncodeRequestContent ( IN CHAR8 *ContentEncodedValue, IN CHAR8 *OriginalContent, OUT VOID **EncodedContent, OUT UINTN *EncodedContentLength ) { EFI_STATUS Status; VOID *EncodedPointer; UINTN EncodedLength; if (OriginalContent == NULL || EncodedContent == NULL || EncodedContentLength == NULL) { return EFI_INVALID_PARAMETER; } Status = RedfishContentEncode ( ContentEncodedValue, OriginalContent, AsciiStrLen (OriginalContent), &EncodedPointer, &EncodedLength ); if (Status == EFI_SUCCESS) { *EncodedContent = EncodedPointer; *EncodedContentLength = EncodedLength; return EFI_SUCCESS; } return Status; } /** This function decodes the content. The Memory block pointed by ContentPointer would be freed and replaced with the cooked Redfish payload. @param[in] ContentEncodedValue HTTP conent encoded value. @param[in, out] ContentPointer Pointer to encoded content. Pointer of decoded content when out. @param[in, out] ContentLength Pointer to the length of encoded content. Length of decoded content when out. @retval EFI_SUCCESS Functinos found. @retval EFI_UNSUPPORTED No functions found. @retval EFI_INVALID_PARAMETER One of the given parameter is invalid. **/ EFI_STATUS DecodeResponseContent ( IN CHAR8 *ContentEncodedValue, IN OUT VOID **ContentPointer, IN OUT UINTN *ContentLength ) { EFI_STATUS Status; VOID *DecodedPointer; UINTN DecodedLength; if (ContentEncodedValue == NULL) { return EFI_INVALID_PARAMETER; } Status = RedfishContentDecode ( ContentEncodedValue, *ContentPointer, *ContentLength, &DecodedPointer, &DecodedLength ); if (Status == EFI_SUCCESS) { FreePool (*ContentPointer); *ContentPointer = DecodedPointer; *ContentLength = DecodedLength; } return Status; } /** Create a HTTP URL string for specific Redfish resource. This function build a URL string from the Redfish Host interface record and caller specified relative path of the resource. Callers are responsible for freeing the returned string storage pointed by HttpUrl. @param[in] RedfishData Redfish network host interface record. @param[in] RelativePath Relative path of a resource. @param[out] HttpUrl The pointer to store the returned URL string. @retval EFI_SUCCESS Build the URL string successfully. @retval EFI_INVALID_PARAMETER RedfishData or HttpUrl is NULL. @retval EFI_OUT_OF_RESOURCES There are not enough memory resources. **/ EFI_STATUS RedfishBuildUrl ( IN REDFISH_CONFIG_SERVICE_INFORMATION *RedfishConfigServiceInfo, IN CHAR16 *RelativePath, OPTIONAL OUT CHAR16 **HttpUrl ) { CHAR16 *Url; CHAR16 *UrlHead; UINTN UrlLength; UINTN PathLen; if ((RedfishConfigServiceInfo == NULL) || (HttpUrl == NULL)) { return EFI_INVALID_PARAMETER; } // // RFC2616: http_URL = "http(s):" "//" host [ ":" port ] [ abs_path [ "?" query ]] // if (RelativePath == NULL) { PathLen = 0; } else { PathLen = StrLen (RelativePath); } UrlLength = StrLen (HTTPS_FLAG) + StrLen (REDFISH_FIRST_URL) + 1 + StrLen(RedfishConfigServiceInfo->RedfishServiceLocation) + PathLen; Url = AllocateZeroPool (UrlLength * sizeof (CHAR16)); if (Url == NULL) { return EFI_OUT_OF_RESOURCES; } UrlHead = Url; // // Copy "http://" or "https://" according RedfishServiceIpPort. // if (!RedfishConfigServiceInfo->RedfishServiceUseHttps) { StrCpyS (Url, StrLen (HTTPS_FLAG) + 1, HTTP_FLAG); Url = Url + StrLen (HTTP_FLAG); } else { StrCpyS (Url, StrLen (HTTPS_FLAG) + 1, HTTPS_FLAG); Url = Url + StrLen (HTTPS_FLAG); } StrCpyS (Url, StrLen (RedfishConfigServiceInfo->RedfishServiceLocation) + 1, RedfishConfigServiceInfo->RedfishServiceLocation); Url = Url + StrLen (RedfishConfigServiceInfo->RedfishServiceLocation); // // Copy abs_path // if (RelativePath != NULL && PathLen != 0 ) { StrnCpyS (Url, UrlLength, RelativePath, PathLen); } *HttpUrl = UrlHead; return EFI_SUCCESS; } redfishService* createServiceEnumerator(REDFISH_CONFIG_SERVICE_INFORMATION *RedfishConfigServiceInfo, const char* rootUri, enumeratorAuthentication* auth, unsigned int flags) { EFI_STATUS Status; CHAR16 *HttpUrl; CHAR8 *AsciiHost; EFI_REST_EX_PROTOCOL *RestEx; redfishService *ret; HttpUrl = NULL; AsciiHost = NULL; RestEx = NULL; ret = NULL; if (RedfishConfigServiceInfo->RedfishServiceRestExHandle == NULL) { goto ON_EXIT; } Status = RedfishBuildUrl(RedfishConfigServiceInfo, NULL, &HttpUrl); if (EFI_ERROR (Status)) { goto ON_EXIT; } ASSERT (HttpUrl != NULL); AsciiHost = UnicodeStrDupToAsciiStr (HttpUrl); if (AsciiHost == NULL) { goto ON_EXIT; } Status = gBS->HandleProtocol ( RedfishConfigServiceInfo->RedfishServiceRestExHandle, &gEfiRestExProtocolGuid, (VOID **)&RestEx ); if (EFI_ERROR (Status)) { goto ON_EXIT; } if(auth == NULL) { ret = createServiceEnumeratorNoAuth(AsciiHost, rootUri, true, flags, RestEx); } else if(auth->authType == REDFISH_AUTH_BASIC) { ret = createServiceEnumeratorBasicAuth(AsciiHost, rootUri, auth->authCodes.userPass.username, auth->authCodes.userPass.password, flags, RestEx); } else if(auth->authType == REDFISH_AUTH_SESSION) { ret = createServiceEnumeratorSessionAuth(AsciiHost, rootUri, auth->authCodes.userPass.username, auth->authCodes.userPass.password, flags, RestEx); } else { goto ON_EXIT; } ret->RestEx = RestEx; ON_EXIT: if (HttpUrl != NULL) { FreePool (HttpUrl); } if (AsciiHost != NULL) { FreePool (AsciiHost); } return ret; } json_t* getUriFromService(redfishService* service, const char* uri, EFI_HTTP_STATUS_CODE** StatusCode) { char* url; json_t* ret; HTTP_IO_HEADER *HttpIoHeader = NULL; EFI_STATUS Status; EFI_HTTP_REQUEST_DATA *RequestData = NULL; EFI_HTTP_MESSAGE *RequestMsg = NULL; EFI_HTTP_MESSAGE ResponseMsg; EFI_HTTP_HEADER *ContentEncodedHeader; if(service == NULL || uri == NULL || StatusCode == NULL) { return NULL; } *StatusCode = NULL; url = makeUrlForService(service, uri); if(!url) { return NULL; } DEBUG((DEBUG_INFO, "libredfish: getUriFromService(): %a\n", url)); // // Step 1: Create HTTP request message with 4 headers: // HttpIoHeader = HttpIoCreateHeader ((service->sessionToken || service->basicAuthStr) ? 6 : 5); if (HttpIoHeader == NULL) { ret = NULL; goto ON_EXIT; } if(service->sessionToken) { Status = HttpIoSetHeader (HttpIoHeader, "X-Auth-Token", service->sessionToken); ASSERT_EFI_ERROR (Status); } else if (service->basicAuthStr) { Status = HttpIoSetHeader (HttpIoHeader, "Authorization", service->basicAuthStr); ASSERT_EFI_ERROR (Status); } Status = HttpIoSetHeader (HttpIoHeader, "Host", service->HostHeaderValue); ASSERT_EFI_ERROR (Status); Status = HttpIoSetHeader (HttpIoHeader, "OData-Version", "4.0"); ASSERT_EFI_ERROR (Status); Status = HttpIoSetHeader (HttpIoHeader, "Accept", "application/json"); ASSERT_EFI_ERROR (Status); Status = HttpIoSetHeader (HttpIoHeader, "User-Agent", "libredfish"); ASSERT_EFI_ERROR (Status); Status = HttpIoSetHeader (HttpIoHeader, "Connection", "Keep-Alive"); ASSERT_EFI_ERROR (Status); // // Step 2: build the rest of HTTP request info. // RequestData = AllocateZeroPool (sizeof (EFI_HTTP_REQUEST_DATA)); if (RequestData == NULL) { ret = NULL; goto ON_EXIT; } RequestData->Method = HttpMethodGet; RequestData->Url = C8ToC16 (url); // // Step 3: fill in EFI_HTTP_MESSAGE // RequestMsg = AllocateZeroPool (sizeof (EFI_HTTP_MESSAGE)); if (RequestMsg == NULL) { ret = NULL; goto ON_EXIT; } RequestMsg->Data.Request = RequestData; RequestMsg->HeaderCount = HttpIoHeader->HeaderCount; RequestMsg->Headers = HttpIoHeader->Headers; ZeroMem (&ResponseMsg, sizeof (ResponseMsg)); // // Step 4: call RESTEx to get response from REST service. // Status = service->RestEx->SendReceive (service->RestEx, RequestMsg, &ResponseMsg); if (EFI_ERROR (Status)) { ret = NULL; goto ON_EXIT; } // // Step 5: Return the HTTP StatusCode and Body message. // if (ResponseMsg.Data.Response != NULL) { *StatusCode = AllocateZeroPool (sizeof (EFI_HTTP_STATUS_CODE)); if (*StatusCode == NULL) { ret = NULL; goto ON_EXIT; } // // The caller shall take the responsibility to free the buffer. // **StatusCode = ResponseMsg.Data.Response->StatusCode; } if (ResponseMsg.BodyLength != 0 && ResponseMsg.Body != NULL) { // // Check if data is encoded. // ContentEncodedHeader = HttpFindHeader (ResponseMsg.HeaderCount, ResponseMsg.Headers, HTTP_HEADER_CONTENT_ENCODING); if (ContentEncodedHeader != NULL) { // // The content is encoded. // Status = DecodeResponseContent (ContentEncodedHeader->FieldValue, &ResponseMsg.Body, &ResponseMsg.BodyLength); if (EFI_ERROR (Status)) { DEBUG ((DEBUG_ERROR, "%a: Failed to decompress the response content %r\n.", __FUNCTION__, Status)); ret = NULL; goto ON_EXIT; } } ret = json_loadb (ResponseMsg.Body, ResponseMsg.BodyLength, 0, NULL); } else { // // There is no message body returned from server. // ret = NULL; } ON_EXIT: if (url != NULL) { free (url); } if (HttpIoHeader != NULL) { HttpIoFreeHeader (HttpIoHeader); } if (RequestData != NULL) { RestConfigFreeHttpRequestData (RequestData); } if (RequestMsg != NULL) { FreePool (RequestMsg); } RestConfigFreeHttpMessage (&ResponseMsg, FALSE); return ret; } json_t* patchUriFromService(redfishService* service, const char* uri, const char* content, EFI_HTTP_STATUS_CODE** StatusCode) { char* url; json_t* ret; HTTP_IO_HEADER *HttpIoHeader = NULL; EFI_STATUS Status; EFI_HTTP_REQUEST_DATA *RequestData = NULL; EFI_HTTP_MESSAGE *RequestMsg = NULL; EFI_HTTP_MESSAGE ResponseMsg; CHAR8 ContentLengthStr[80]; CHAR8 *EncodedContent; UINTN EncodedContentLen; if(service == NULL || uri == NULL || content == NULL || StatusCode == NULL) { return NULL; } *StatusCode = NULL; url = makeUrlForService(service, uri); if(!url) { return NULL; } DEBUG((DEBUG_INFO, "libredfish: patchUriFromService(): %a\n", url)); // // Step 1: Create HTTP request message with 4 headers: // HttpIoHeader = HttpIoCreateHeader ((service->sessionToken || service->basicAuthStr) ? 9 : 8); if (HttpIoHeader == NULL) { ret = NULL; goto ON_EXIT; } if(service->sessionToken) { Status = HttpIoSetHeader (HttpIoHeader, "X-Auth-Token", service->sessionToken); ASSERT_EFI_ERROR (Status); } else if (service->basicAuthStr) { Status = HttpIoSetHeader (HttpIoHeader, "Authorization", service->basicAuthStr); ASSERT_EFI_ERROR (Status); } Status = HttpIoSetHeader (HttpIoHeader, "Host", service->HostHeaderValue); ASSERT_EFI_ERROR (Status); Status = HttpIoSetHeader (HttpIoHeader, "Content-Type", "application/json"); ASSERT_EFI_ERROR (Status); Status = HttpIoSetHeader (HttpIoHeader, "Accept", "application/json"); ASSERT_EFI_ERROR (Status); Status = HttpIoSetHeader (HttpIoHeader, "User-Agent", "libredfish"); ASSERT_EFI_ERROR (Status); Status = HttpIoSetHeader (HttpIoHeader, "Connection", "Keep-Alive"); ASSERT_EFI_ERROR (Status); AsciiSPrint( ContentLengthStr, sizeof (ContentLengthStr), "%lu", (UINT64) strlen(content) ); Status = HttpIoSetHeader (HttpIoHeader, "Content-Length", ContentLengthStr); ASSERT_EFI_ERROR (Status); Status = HttpIoSetHeader (HttpIoHeader, "OData-Version", "4.0"); ASSERT_EFI_ERROR (Status); // // Step 2: build the rest of HTTP request info. // RequestData = AllocateZeroPool (sizeof (EFI_HTTP_REQUEST_DATA)); if (RequestData == NULL) { ret = NULL; goto ON_EXIT; } RequestData->Method = HttpMethodPatch; RequestData->Url = C8ToC16 (url); // // Step 3: fill in EFI_HTTP_MESSAGE // RequestMsg = AllocateZeroPool (sizeof (EFI_HTTP_MESSAGE)); if (RequestMsg == NULL) { ret = NULL; goto ON_EXIT; } EncodedContent = (CHAR8 *)content; EncodedContentLen = strlen(content); // // We currently only support gzip Content-Encoding. // Status = EncodeRequestContent ((CHAR8 *)HTTP_CONTENT_ENCODING_GZIP, (CHAR8 *)content, (VOID **)&EncodedContent, &EncodedContentLen); if (Status == EFI_INVALID_PARAMETER) { DEBUG((DEBUG_ERROR, "%a: Error to encode content.\n", __FUNCTION__)); ret = NULL; goto ON_EXIT; } else if (Status == EFI_UNSUPPORTED) { DEBUG((DEBUG_INFO, "No content coding for %a! Use raw data instead.\n", HTTP_CONTENT_ENCODING_GZIP)); Status = HttpIoSetHeader (HttpIoHeader, "Content-Encoding", HTTP_CONTENT_ENCODING_IDENTITY); ASSERT_EFI_ERROR (Status); } else { Status = HttpIoSetHeader (HttpIoHeader, "Content-Encoding", HTTP_CONTENT_ENCODING_GZIP); ASSERT_EFI_ERROR (Status); } RequestMsg->Data.Request = RequestData; RequestMsg->HeaderCount = HttpIoHeader->HeaderCount; RequestMsg->Headers = HttpIoHeader->Headers; RequestMsg->BodyLength = EncodedContentLen; RequestMsg->Body = (VOID*) EncodedContent; ZeroMem (&ResponseMsg, sizeof (ResponseMsg)); // // Step 4: call RESTEx to get response from REST service. // Status = service->RestEx->SendReceive (service->RestEx, RequestMsg, &ResponseMsg); if (EFI_ERROR (Status)) { ret = NULL; goto ON_EXIT; } // // Step 5: Return the HTTP StatusCode and Body message. // if (ResponseMsg.Data.Response != NULL) { *StatusCode = AllocateZeroPool (sizeof (EFI_HTTP_STATUS_CODE)); if (*StatusCode == NULL) { ret = NULL; goto ON_EXIT; } // // The caller shall take the responsibility to free the buffer. // **StatusCode = ResponseMsg.Data.Response->StatusCode; } if (EncodedContent != content) { FreePool (EncodedContent); } if (ResponseMsg.BodyLength != 0 && ResponseMsg.Body != NULL) { ret = json_loadb (ResponseMsg.Body, ResponseMsg.BodyLength, 0, NULL); } else { // // There is no message body returned from server. // ret = NULL; } ON_EXIT: if (url != NULL) { free (url); } if (HttpIoHeader != NULL) { HttpIoFreeHeader (HttpIoHeader); } if (RequestData != NULL) { RestConfigFreeHttpRequestData (RequestData); } if (RequestMsg != NULL) { FreePool (RequestMsg); } RestConfigFreeHttpMessage (&ResponseMsg, FALSE); return ret; } json_t* postUriFromService(redfishService* service, const char* uri, const char* content, size_t contentLength, const char* contentType, EFI_HTTP_STATUS_CODE** StatusCode) { char* url = NULL; json_t* ret; HTTP_IO_HEADER *HttpIoHeader = NULL; EFI_STATUS Status; EFI_HTTP_REQUEST_DATA *RequestData = NULL; EFI_HTTP_MESSAGE *RequestMsg = NULL; EFI_HTTP_MESSAGE ResponseMsg; CHAR8 ContentLengthStr[80]; EFI_HTTP_HEADER *HttpHeader = NULL; ret = NULL; if(service == NULL || uri == NULL || content == NULL || StatusCode == NULL) { return NULL; } *StatusCode = NULL; url = makeUrlForService(service, uri); if(!url) { return NULL; } DEBUG((DEBUG_INFO, "libredfish: postUriFromService(): %a\n", url)); if(contentLength == 0) { contentLength = strlen(content); } // // Step 1: Create HTTP request message with 4 headers: // HttpIoHeader = HttpIoCreateHeader ((service->sessionToken || service->basicAuthStr) ? 8 : 7); if (HttpIoHeader == NULL) { goto ON_EXIT; } if(service->sessionToken) { Status = HttpIoSetHeader (HttpIoHeader, "X-Auth-Token", service->sessionToken); ASSERT_EFI_ERROR (Status); } else if (service->basicAuthStr) { Status = HttpIoSetHeader (HttpIoHeader, "Authorization", service->basicAuthStr); ASSERT_EFI_ERROR (Status); } if(contentType == NULL) { Status = HttpIoSetHeader (HttpIoHeader, "Content-Type", "application/json"); ASSERT_EFI_ERROR (Status); } else { Status = HttpIoSetHeader (HttpIoHeader, "Content-Type", (CHAR8 *) contentType); ASSERT_EFI_ERROR (Status); } Status = HttpIoSetHeader (HttpIoHeader, "Host", service->HostHeaderValue); ASSERT_EFI_ERROR (Status); Status = HttpIoSetHeader (HttpIoHeader, "Accept", "application/json"); ASSERT_EFI_ERROR (Status); Status = HttpIoSetHeader (HttpIoHeader, "User-Agent", "libredfish"); ASSERT_EFI_ERROR (Status); Status = HttpIoSetHeader (HttpIoHeader, "Connection", "Keep-Alive"); ASSERT_EFI_ERROR (Status); AsciiSPrint( ContentLengthStr, sizeof (ContentLengthStr), "%lu", (UINT64) contentLength ); Status = HttpIoSetHeader (HttpIoHeader, "Content-Length", ContentLengthStr); ASSERT_EFI_ERROR (Status); Status = HttpIoSetHeader (HttpIoHeader, "OData-Version", "4.0"); ASSERT_EFI_ERROR (Status); // // Step 2: build the rest of HTTP request info. // RequestData = AllocateZeroPool (sizeof (EFI_HTTP_REQUEST_DATA)); if (RequestData == NULL) { goto ON_EXIT; } RequestData->Method = HttpMethodPost; RequestData->Url = C8ToC16 (url); // // Step 3: fill in EFI_HTTP_MESSAGE // RequestMsg = AllocateZeroPool (sizeof (EFI_HTTP_MESSAGE)); if (RequestMsg == NULL) { goto ON_EXIT; } RequestMsg->Data.Request = RequestData; RequestMsg->HeaderCount = HttpIoHeader->HeaderCount; RequestMsg->Headers = HttpIoHeader->Headers; RequestMsg->BodyLength = contentLength; RequestMsg->Body = (VOID*) content; ZeroMem (&ResponseMsg, sizeof (ResponseMsg)); // // Step 4: call RESTEx to get response from REST service. // Status = service->RestEx->SendReceive (service->RestEx, RequestMsg, &ResponseMsg); if (EFI_ERROR (Status)) { goto ON_EXIT; } // // Step 5: Return the HTTP StatusCode and Body message. // if (ResponseMsg.Data.Response != NULL) { *StatusCode = AllocateZeroPool (sizeof (EFI_HTTP_STATUS_CODE)); if (*StatusCode == NULL) { goto ON_EXIT; } // // The caller shall take the responsibility to free the buffer. // **StatusCode = ResponseMsg.Data.Response->StatusCode; } if (ResponseMsg.BodyLength != 0 && ResponseMsg.Body != NULL) { ret = json_loadb (ResponseMsg.Body, ResponseMsg.BodyLength, 0, NULL); } // // Step 6: Parsing the HttpHeader to retrive the X-Auth-Token if the HTTP StatusCode is correct. // if (ResponseMsg.Data.Response->StatusCode == HTTP_STATUS_200_OK || ResponseMsg.Data.Response->StatusCode == HTTP_STATUS_204_NO_CONTENT) { HttpHeader = HttpFindHeader (ResponseMsg.HeaderCount, ResponseMsg.Headers, "X-Auth-Token"); if (HttpHeader != NULL) { if(service->sessionToken) { free(service->sessionToken); } service->sessionToken = AllocateCopyPool (AsciiStrSize (HttpHeader->FieldValue), HttpHeader->FieldValue); } /* // // Below opeation seems to be unnecessary. // Besides, the FieldValue for the Location is the full HTTP URI (Http://0.0.0.0:5000/XXX), so we can't use it as the // parameter of getUriFromService () directly. // HttpHeader = HttpFindHeader (ResponseMsg.HeaderCount, ResponseMsg.Headers, "Location"); if (HttpHeader != NULL) { ret = getUriFromService(service, HttpHeader->FieldValue); goto ON_EXIT; } */ } ON_EXIT: if (url != NULL) { free (url); } if (HttpIoHeader != NULL) { HttpIoFreeHeader (HttpIoHeader); } if (RequestData != NULL) { RestConfigFreeHttpRequestData (RequestData); } if (RequestMsg != NULL) { FreePool (RequestMsg); } RestConfigFreeHttpMessage (&ResponseMsg, FALSE); return ret; } json_t* deleteUriFromService(redfishService* service, const char* uri, EFI_HTTP_STATUS_CODE** StatusCode) { char* url; json_t* ret; HTTP_IO_HEADER *HttpIoHeader = NULL; EFI_STATUS Status; EFI_HTTP_REQUEST_DATA *RequestData = NULL; EFI_HTTP_MESSAGE *RequestMsg = NULL; EFI_HTTP_MESSAGE ResponseMsg; ret = NULL; if(service == NULL || uri == NULL || StatusCode == NULL) { return NULL; } *StatusCode = NULL; url = makeUrlForService(service, uri); if(!url) { return NULL; } DEBUG((DEBUG_INFO, "libredfish: deleteUriFromService(): %a\n", url)); // // Step 1: Create HTTP request message with 4 headers: // HttpIoHeader = HttpIoCreateHeader ((service->sessionToken || service->basicAuthStr) ? 5 : 4); if (HttpIoHeader == NULL) { ret = NULL; goto ON_EXIT; } if(service->sessionToken) { Status = HttpIoSetHeader (HttpIoHeader, "X-Auth-Token", service->sessionToken); ASSERT_EFI_ERROR (Status); } else if (service->basicAuthStr) { Status = HttpIoSetHeader (HttpIoHeader, "Authorization", service->basicAuthStr); ASSERT_EFI_ERROR (Status); } Status = HttpIoSetHeader (HttpIoHeader, "Host", service->HostHeaderValue); ASSERT_EFI_ERROR (Status); Status = HttpIoSetHeader (HttpIoHeader, "User-Agent", "libredfish"); ASSERT_EFI_ERROR (Status); Status = HttpIoSetHeader (HttpIoHeader, "OData-Version", "4.0"); ASSERT_EFI_ERROR (Status); Status = HttpIoSetHeader (HttpIoHeader, "Connection", "Keep-Alive"); ASSERT_EFI_ERROR (Status); // // Step 2: build the rest of HTTP request info. // RequestData = AllocateZeroPool (sizeof (EFI_HTTP_REQUEST_DATA)); if (RequestData == NULL) { ret = NULL; goto ON_EXIT; } RequestData->Method = HttpMethodDelete; RequestData->Url = C8ToC16 (url); // // Step 3: fill in EFI_HTTP_MESSAGE // RequestMsg = AllocateZeroPool (sizeof (EFI_HTTP_MESSAGE)); if (RequestMsg == NULL) { ret = NULL; goto ON_EXIT; } RequestMsg->Data.Request = RequestData; RequestMsg->HeaderCount = HttpIoHeader->HeaderCount; RequestMsg->Headers = HttpIoHeader->Headers; ZeroMem (&ResponseMsg, sizeof (ResponseMsg)); // // Step 4: call RESTEx to get response from REST service. // Status = service->RestEx->SendReceive (service->RestEx, RequestMsg, &ResponseMsg); if (EFI_ERROR (Status)) { ret = NULL; goto ON_EXIT; } // // Step 5: Return the HTTP StatusCode and Body message. // if (ResponseMsg.Data.Response != NULL) { *StatusCode = AllocateZeroPool (sizeof (EFI_HTTP_STATUS_CODE)); if (*StatusCode == NULL) { ret = NULL; goto ON_EXIT; } // // The caller shall take the responsibility to free the buffer. // **StatusCode = ResponseMsg.Data.Response->StatusCode; } if (ResponseMsg.BodyLength != 0 && ResponseMsg.Body != NULL) { ret = json_loadb (ResponseMsg.Body, ResponseMsg.BodyLength, 0, NULL); } ON_EXIT: if (url != NULL) { free (url); } if (HttpIoHeader != NULL) { HttpIoFreeHeader (HttpIoHeader); } if (RequestData != NULL) { RestConfigFreeHttpRequestData (RequestData); } if (RequestMsg != NULL) { FreePool (RequestMsg); } RestConfigFreeHttpMessage (&ResponseMsg, FALSE); return ret; } redfishPayload* getRedfishServiceRoot(redfishService* service, const char* version, EFI_HTTP_STATUS_CODE** StatusCode) { json_t* value; json_t* versionNode; const char* verUrl; if(version == NULL) { versionNode = json_object_get(service->versions, "v1"); } else { versionNode = json_object_get(service->versions, version); } if(versionNode == NULL) { return NULL; } verUrl = json_string_value(versionNode); if(verUrl == NULL) { return NULL; } value = getUriFromService(service, verUrl, StatusCode); if(value == NULL) { if((service->flags & REDFISH_FLAG_SERVICE_NO_VERSION_DOC) == 0) { json_decref(versionNode); } return NULL; } return createRedfishPayload(value, service); } redfishPayload* getPayloadByPath(redfishService* service, const char* path, EFI_HTTP_STATUS_CODE** StatusCode) { redPathNode* redpath; redfishPayload* root; redfishPayload* ret; if(!service || !path || StatusCode == NULL) { return NULL; } *StatusCode = NULL; redpath = parseRedPath(path); if(!redpath) { return NULL; } if(!redpath->isRoot) { cleanupRedPath(redpath); return NULL; } root = getRedfishServiceRoot(service, redpath->version, StatusCode); if (*StatusCode == NULL || **StatusCode < HTTP_STATUS_200_OK || **StatusCode > HTTP_STATUS_206_PARTIAL_CONTENT) { cleanupRedPath(redpath); return root; } if(redpath->next == NULL) { cleanupRedPath(redpath); return root; } FreePool (*StatusCode); *StatusCode = NULL; ret = getPayloadForPath(root, redpath->next, StatusCode); if (*StatusCode == NULL && ret != NULL) { // // In such a case, the Redfish resource is parsed from the input payload (root) directly. // So, we still return HTTP_STATUS_200_OK. // *StatusCode = AllocateZeroPool (sizeof (EFI_HTTP_STATUS_CODE)); if (*StatusCode == NULL) { ret = NULL; } else { **StatusCode = HTTP_STATUS_200_OK; } } cleanupPayload(root); cleanupRedPath(redpath); return ret; } void cleanupServiceEnumerator(redfishService* service) { if(!service) { return; } free(service->host); json_decref(service->versions); if(service->sessionToken != NULL) { ZeroMem (service->sessionToken, (UINTN)strlen(service->sessionToken)); FreePool(service->sessionToken); } if (service->basicAuthStr != NULL) { ZeroMem (service->basicAuthStr, (UINTN)strlen(service->basicAuthStr)); FreePool (service->basicAuthStr); } free(service); } static int initRest(redfishService* service, void * restProtocol) { service->RestEx = restProtocol; return 0; } static redfishService* createServiceEnumeratorNoAuth(const char* host, const char* rootUri, bool enumerate, unsigned int flags, void * restProtocol) { redfishService* ret; char *HostStart; ret = (redfishService*)calloc(1, sizeof(redfishService)); ZeroMem (ret, sizeof(redfishService)); if(initRest(ret, restProtocol) != 0) { free(ret); return NULL; } ret->host = AllocateCopyPool(AsciiStrSize(host), host); ret->flags = flags; if(enumerate) { ret->versions = getVersions(ret, rootUri); } HostStart = strstr (ret->host, "//"); if (HostStart != NULL && (*(HostStart + 2) != '\0')) { ret->HostHeaderValue = HostStart + 2; } return ret; } EFI_STATUS createBasicAuthStr ( IN redfishService* service, IN CONST CHAR8 *UserId, IN CONST CHAR8 *Password ) { EFI_STATUS Status; CHAR8 *RawAuthValue; UINTN RawAuthBufSize; CHAR8 *EnAuthValue; UINTN EnAuthValueSize; CHAR8 *BasicWithEnAuthValue; UINTN BasicBufSize; EnAuthValue = NULL; EnAuthValueSize = 0; RawAuthBufSize = AsciiStrLen (UserId) + AsciiStrLen (Password) + 2; RawAuthValue = AllocatePool (RawAuthBufSize); if (RawAuthValue == NULL) { return EFI_OUT_OF_RESOURCES; } // // Build raw AuthValue (UserId:Password). // AsciiSPrint ( RawAuthValue, RawAuthBufSize, "%a:%a", UserId, Password ); // // Encoding RawAuthValue into Base64 format. // Status = Base64Encode ( (CONST UINT8 *) RawAuthValue, AsciiStrLen (RawAuthValue), EnAuthValue, &EnAuthValueSize ); if (Status == EFI_BUFFER_TOO_SMALL) { EnAuthValue = (CHAR8 *) AllocateZeroPool (EnAuthValueSize); if (EnAuthValue == NULL) { Status = EFI_OUT_OF_RESOURCES; return Status; } Status = Base64Encode ( (CONST UINT8 *) RawAuthValue, AsciiStrLen (RawAuthValue), EnAuthValue, &EnAuthValueSize ); } if (EFI_ERROR (Status)) { goto Exit; } BasicBufSize = AsciiStrLen ("Basic ") + AsciiStrLen(EnAuthValue) + 2; BasicWithEnAuthValue = AllocatePool (BasicBufSize); if (BasicWithEnAuthValue == NULL) { Status = EFI_OUT_OF_RESOURCES; goto Exit; } // // Build encoded EnAuthValue with Basic (Basic EnAuthValue). // AsciiSPrint ( BasicWithEnAuthValue, BasicBufSize, "%a %a", "Basic", EnAuthValue ); service->basicAuthStr = BasicWithEnAuthValue; Exit: if (RawAuthValue != NULL) { ZeroMem (RawAuthValue, RawAuthBufSize); FreePool (RawAuthValue); } if (EnAuthValue != NULL) { ZeroMem (EnAuthValue, EnAuthValueSize); FreePool (EnAuthValue); } return Status; } static redfishService* createServiceEnumeratorBasicAuth(const char* host, const char* rootUri, const char* username, const char* password, unsigned int flags, void * restProtocol) { redfishService* ret; EFI_STATUS Status; ret = createServiceEnumeratorNoAuth(host, rootUri, false, flags, restProtocol); // add basic auth str Status = createBasicAuthStr (ret, username, password); if (EFI_ERROR(Status)) { cleanupServiceEnumerator (ret); return NULL; } ret->versions = getVersions(ret, rootUri); return ret; } static redfishService* createServiceEnumeratorSessionAuth(const char* host, const char* rootUri, const char* username, const char* password, unsigned int flags, void * restProtocol) { redfishService* ret; redfishPayload* payload; redfishPayload* links; json_t* sessionPayload; json_t* session; json_t* odataId; const char* uri; json_t* post; char* content; EFI_HTTP_STATUS_CODE *StatusCode; content = NULL; StatusCode = NULL; ret = createServiceEnumeratorNoAuth(host, rootUri, true, flags, restProtocol); if(ret == NULL) { return NULL; } payload = getRedfishServiceRoot(ret, NULL, &StatusCode); if(StatusCode == NULL || *StatusCode < HTTP_STATUS_200_OK || *StatusCode > HTTP_STATUS_206_PARTIAL_CONTENT) { if (StatusCode != NULL) { FreePool (StatusCode); } if (payload != NULL) { cleanupPayload(payload); } cleanupServiceEnumerator(ret); return NULL; } if (StatusCode != NULL) { FreePool (StatusCode); StatusCode = NULL; } links = getPayloadByNodeName(payload, "Links", &StatusCode); cleanupPayload(payload); if(links == NULL) { cleanupServiceEnumerator(ret); return NULL; } session = json_object_get(links->json, "Sessions"); if(session == NULL) { cleanupPayload(links); cleanupServiceEnumerator(ret); return NULL; } odataId = json_object_get(session, "@odata.id"); if(odataId == NULL) { cleanupPayload(links); cleanupServiceEnumerator(ret); return NULL; } uri = json_string_value(odataId); post = json_object(); addStringToJsonObject(post, "UserName", username); addStringToJsonObject(post, "Password", password); content = json_dumps(post, 0); json_decref(post); sessionPayload = postUriFromService(ret, uri, content, 0, NULL, &StatusCode); if (content != NULL) { ZeroMem (content, (UINTN)strlen(content)); free(content); } if(sessionPayload == NULL || StatusCode == NULL || *StatusCode < HTTP_STATUS_200_OK || *StatusCode > HTTP_STATUS_206_PARTIAL_CONTENT) { //Failed to create session! cleanupPayload(links); cleanupServiceEnumerator(ret); if (StatusCode != NULL) { FreePool (StatusCode); } if (sessionPayload != NULL) { json_decref(sessionPayload); } return NULL; } json_decref(sessionPayload); cleanupPayload(links); FreePool (StatusCode); return ret; } static char* makeUrlForService(redfishService* service, const char* uri) { char* url; if(service->host == NULL) { return NULL; } url = (char*)malloc(strlen(service->host)+strlen(uri)+1); strcpy(url, service->host); strcat(url, uri); return url; } static json_t* getVersions(redfishService* service, const char* rootUri) { json_t* ret = NULL; EFI_HTTP_STATUS_CODE* StatusCode = NULL; if(service->flags & REDFISH_FLAG_SERVICE_NO_VERSION_DOC) { service->versions = json_object(); if(service->versions == NULL) { return NULL; } addStringToJsonObject(service->versions, "v1", "/redfish/v1"); return service->versions; } if(rootUri != NULL) { ret = getUriFromService(service, rootUri, &StatusCode); } else { ret = getUriFromService(service, "/redfish", &StatusCode); } if (ret == NULL || StatusCode == NULL || *StatusCode < HTTP_STATUS_200_OK || *StatusCode > HTTP_STATUS_206_PARTIAL_CONTENT) { if (ret != NULL) { json_decref(ret); } ret = NULL; } if (StatusCode != NULL) { FreePool (StatusCode); } return ret; } static void addStringToJsonObject(json_t* object, const char* key, const char* value) { json_t* jValue = json_string(value); json_object_set(object, key, jValue); json_decref(jValue); }
28.556908
183
0.621397
89b05981e982946e6cd65af88a93b596ceef00dd
1,363
h
C
IoTGateWay/bsp/stm32/stm32f105RC/application/config/appconfig.h
JoshWorld/WhaleShark_IIoT
6728815caa369c798074022536878d1fdc5ef871
[ "Apache-2.0" ]
1
2020-10-20T15:40:53.000Z
2020-10-20T15:40:53.000Z
IoTGateWay/bsp/stm32/stm32f105RC/application/config/appconfig.h
JoshWorld/WhaleShark_IIoT
6728815caa369c798074022536878d1fdc5ef871
[ "Apache-2.0" ]
null
null
null
IoTGateWay/bsp/stm32/stm32f105RC/application/config/appconfig.h
JoshWorld/WhaleShark_IIoT
6728815caa369c798074022536878d1fdc5ef871
[ "Apache-2.0" ]
1
2020-08-12T15:42:45.000Z
2020-08-12T15:42:45.000Z
/* * File : appconfig.h */ /** * @addtogroup STM32 */ /*@{*/ #ifndef __APPCONFIG_H__ #define __APPCONFIG_H__ #include <board.h> /* software version */ #define SVER_MAJOR 1 #define SVER_MINOR 0 #define SVER_BUILD 1 #define MODEL_NAME "SA-100" #define PRODUCT_NAME "Spiretech" /* Uart name */ #define UART2_DEV_NAME "uart2" #define UART3_DEV_NAME "uart3" #define UART5_DEV_NAME "uart5" #define UART2_PORT UART2_DEV_NAME #define UART3_PORT UART3_DEV_NAME #define UART5_PORT UART5_DEV_NAME /*rt-thread stack size*/ #define APPLICATION_STACK_SIZE 1024U #define USBCONSOLE_STACK_SIZE 1024U #define PLCCOMMM_STACK_SIZE 1024U #define WIFI_RX_STACK_SZIE 1024U #define NETWORKMANAGER_STACK_SIZE 1024U #define MANUFACTURE_CONTROL_STACK_SIZE 1024U /**/ #define CR '\r' // 0x0D #define LF '\n' // 0x0A #define SP 0x20 // space #define STX 0x02 #define ETX 0x03 /* TLV ID */ #define DEFAULT_SSID "STI_IOT" #define DEFAULT_PASSWORD "!sti_iot!" #define DEFAULT_IP "0.0.0.0" #define DEFAULT_MAC "00:00:00:00:00:00" #define DEFAULT_DEVICE "TS0000" //Default Device Info #define DEFAULT_DOMAIN "onsite-monitor.xip.kr" #endif /* __APPCONFIG_H__ */ /*@}*/
23.5
58
0.636097
071c40fdb38be825045bfe9320991628553595e3
1,318
c
C
Project-one/src/semaphores-lib.c
carvalheirafc/cDump
6a61b914d47f0df6296a3cf22ae7cfd8172b9ffc
[ "Apache-2.0" ]
null
null
null
Project-one/src/semaphores-lib.c
carvalheirafc/cDump
6a61b914d47f0df6296a3cf22ae7cfd8172b9ffc
[ "Apache-2.0" ]
null
null
null
Project-one/src/semaphores-lib.c
carvalheirafc/cDump
6a61b914d47f0df6296a3cf22ae7cfd8172b9ffc
[ "Apache-2.0" ]
null
null
null
#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <time.h> #include <pthread.h> #include "semaphores-lib.h" // Global Variables Declarations int **matrix_one, **matrix_two; int **matrix_result; void fillMatrix(int** targetMatrix, int number, int matrix_size){ int ROWS = matrix_size; int COLUMNS = matrix_size; if(number == -1){ srand(time(NULL)); for(int i = 0; i < ROWS; i++){ for(int j = 0; j < COLUMNS; j++){ targetMatrix[i][j] = rand(); } } } else{ for(int i = 0; i < ROWS; i++){ for(int j = 0; j < COLUMNS; j++){ targetMatrix[i][j] = number; } } } } void matrixAlloc(int** matrix_to_alloc, int size){ matrix_to_alloc = (int **) malloc(size * sizeof(int*)); matrix_to_alloc[0] = (int *) malloc(size * sizeof(int)); } void matrixMultiplicationWithTreads(int matrix_size){ pthread_t *threads; matrixAlloc(matrix_one, matrix_size); matrixAlloc(matrix_two, matrix_size); matrixAlloc(matrix_result, matrix_size); threads = (pthread_t *) malloc(matrix_size * sizeof(pthread_t)); fillMatrix(matrix_one, 2, matrix_size); //fillMatrix(matrix_two, 3, matrix_size); /* for(int i = 0; i < matrix_size; i++){ //pthread_create(&threads[i], NULL, SummationProccess, (void*) (size_t)i); pthread_join(threads[i], 0); }*/ }
19.101449
76
0.653263
8e35dd68ce1a29d4f669fb5832ed079c9ead4676
1,778
h
C
src/Manager/AssetMgr.h
ounols/CSEngine
beebdede6eb223c1ec3ec533ed0eb03b80f68a3b
[ "BSD-2-Clause" ]
37
2021-05-19T12:23:57.000Z
2022-03-21T23:51:30.000Z
src/Manager/AssetMgr.h
ounols/CSEngine
beebdede6eb223c1ec3ec533ed0eb03b80f68a3b
[ "BSD-2-Clause" ]
3
2021-10-12T11:12:52.000Z
2021-11-28T16:11:19.000Z
src/Manager/AssetMgr.h
ounols/CSEngine
beebdede6eb223c1ec3ec533ed0eb03b80f68a3b
[ "BSD-2-Clause" ]
4
2021-09-16T15:17:42.000Z
2021-10-02T21:29:38.000Z
// // Created by ounols on 19. 6. 6. // //참조 : https://codingcoding.tistory.com/900 #pragma once #include <string> #include <vector> #include "../Util/Loader/ZIP/zip.h" #ifdef __ANDROID__ #include <android/asset_manager.h> #include <jni.h> #endif namespace CSE { class AssetMgr { public: enum TYPE { NONE, TEX_2D, TEX_CUBEMAP, TEX_FRAMEBUFFER, MATERIAL, DAE, PREFAB, SCENE, SCRIPT, TXT, SHADER, SHADER_HANDLE, INI }; struct AssetReference { std::string path; std::string name; std::string id; std::string name_full; std::string extension; TYPE type = NONE; }; public: AssetMgr(); ~AssetMgr(); void Exterminate(); void LoadAssets(bool isPacked); AssetReference* GetAsset(std::string name) const; std::vector<AssetReference*> GetAssets(TYPE type) const; static std::string LoadAssetFile(const std::string& path); #ifdef __ANDROID__ void SetAssetManager(AAssetManager* obj); AAssetManager* GetAssetManager(); void SetEnv(JNIEnv* obj); JNIEnv* GetEnv(); #endif private: void ReadDirectory(const std::string& path); void ReadPackage(const std::string& path); AssetReference* CreateAsset(const std::string& path, const std::string& name_full, std::string name = ""); void SetType(); static AssetReference* AppendSubName(AssetReference* asset, const std::string& sub_name); private: std::vector<AssetReference*> m_assets; zip_t* m_zip = nullptr; #ifdef __ANDROID__ AAssetManager* m_assetManager; JNIEnv* m_env = nullptr; std::string m_package_raw; #endif }; }
24.027027
125
0.616985
8e762d683e5057ee924cce401927540be3dae7d6
1,326
h
C
drivers/gpu/drm/i915/gt/intel_engine_stats.h
Sunrisepeak/Linux2.6-Reading
c25102a494a37f9f30a27ca2cd4a1a412bffc80f
[ "MIT" ]
44
2022-03-16T08:32:31.000Z
2022-03-31T16:02:35.000Z
drivers/gpu/drm/i915/gt/intel_engine_stats.h
Sunrisepeak/Linux2.6-Reading
c25102a494a37f9f30a27ca2cd4a1a412bffc80f
[ "MIT" ]
1
2022-03-29T02:30:28.000Z
2022-03-30T03:40:46.000Z
drivers/gpu/drm/i915/gt/intel_engine_stats.h
Sunrisepeak/Linux2.6-Reading
c25102a494a37f9f30a27ca2cd4a1a412bffc80f
[ "MIT" ]
18
2022-03-19T04:41:04.000Z
2022-03-31T03:32:12.000Z
/* SPDX-License-Identifier: MIT */ /* * Copyright © 2020 Intel Corporation */ #ifndef __INTEL_ENGINE_STATS_H__ #define __INTEL_ENGINE_STATS_H__ #include <linux/atomic.h> #include <linux/ktime.h> #include <linux/seqlock.h> #include "i915_gem.h" /* GEM_BUG_ON */ #include "intel_engine.h" static inline void intel_engine_context_in(struct intel_engine_cs *engine) { struct intel_engine_execlists_stats *stats = &engine->stats.execlists; unsigned long flags; if (stats->active) { stats->active++; return; } /* The writer is serialised; but the pmu reader may be from hardirq */ local_irq_save(flags); write_seqcount_begin(&stats->lock); stats->start = ktime_get(); stats->active++; write_seqcount_end(&stats->lock); local_irq_restore(flags); GEM_BUG_ON(!stats->active); } static inline void intel_engine_context_out(struct intel_engine_cs *engine) { struct intel_engine_execlists_stats *stats = &engine->stats.execlists; unsigned long flags; GEM_BUG_ON(!stats->active); if (stats->active > 1) { stats->active--; return; } local_irq_save(flags); write_seqcount_begin(&stats->lock); stats->active--; stats->total = ktime_add(stats->total, ktime_sub(ktime_get(), stats->start)); write_seqcount_end(&stats->lock); local_irq_restore(flags); } #endif /* __INTEL_ENGINE_STATS_H__ */
21.387097
75
0.736802
b03cbf13695ccef0478a9d2ee1ea22d439955b8e
2,463
h
C
Source/Plugins/UIPlugins/QtPlugin/header/QtHelper.h
OscarGame/blade
6987708cb011813eb38e5c262c7a83888635f002
[ "MIT" ]
146
2018-12-03T08:08:17.000Z
2022-03-21T06:04:06.000Z
Source/Plugins/UIPlugins/QtPlugin/header/QtHelper.h
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
1
2019-01-18T03:35:49.000Z
2019-01-18T03:36:08.000Z
Source/Plugins/UIPlugins/QtPlugin/header/QtHelper.h
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
31
2018-12-03T10:32:43.000Z
2021-10-04T06:31:44.000Z
/******************************************************************** created: 2016/07/27 filename: QtHelper.h author: Crazii purpose: *********************************************************************/ #ifndef __Blade_QtHelper_h__ #define __Blade_QtHelper_h__ namespace Blade { //need unicode build to bridge with QChar static_assert(sizeof(QChar) == sizeof(tchar), "need unicode build, define UNICODE or _UNICODE."); ////////////////////////////////////////////////////////////////////////// static inline QString TString2QString(const TString& btstr) { return QString( (QChar*)btstr.c_str(), btstr.size() ); } ////////////////////////////////////////////////////////////////////////// static inline TString QString2TString(const QString& qstr) { return TString( (tchar*)qstr.constData() ); } ////////////////////////////////////////////////////////////////////////// static inline QString TranslateQString(const QString& qstr) { return TString2QString(BTString2Lang(QString2TString(qstr))); } ////////////////////////////////////////////////////////////////////////// static inline QStringList TranslateQStrings(const QStringList& qstrList) { QStringList ret; ret.reserve(qstrList.count()); for(int i = 0; i < qstrList.count(); ++i) ret.append(TranslateQString(qstrList[i])); return ret; } //functors for None QObject derived class's member function template<typename T, typename V> struct FnMember1 { public: typedef void (T::*memFun)(V); T* mTarget; memFun mFn; FnMember1(T* target, memFun fn) :mTarget(target), mFn(fn) {} void operator()(V v) { (mTarget->*mFn)(v); } }; template<typename T, typename V> static inline FnMember1<T, V> makeMemFn(T* target, void (T::*fn)(V)) { return FnMember1<T, V>(target, fn); } template<typename T> struct FnMember1<T, void> { typedef void (T::*memFun)(void); T* mTarget; memFun mFn; FnMember1(T* target, memFun fn) :mTarget(target), mFn(fn) {} void operator()(void) { (mTarget->*mFn)(); } }; ////////////////////////////////////////////////////////////////////////// template<typename T> static inline FnMember1<T, void> makeMemFn(T* t, void (T::*fn)(void)) { return FnMember1<T, void>(t, fn); } /** @brief */ QImage::Format toQImageFormat(PixelFormat format); /** @brief */ Handle<QImage> toQImage(const HIMAGE& img); }//namespace Blade #define QT_NEW BLADE_NEW #endif // __Blade_QtHelper_h__
24.63
98
0.544052
b0901ab46e19139f0bee253b0e29d63e7038e835
1,775
h
C
include/btle/siLabsBgApi/cxa_siLabsBgApi_btle_central.h
OpenCXA/common-c
0f7b401aff141c8b8df867f0cff5f31f6a1ee4cf
[ "MIT" ]
8
2019-08-30T15:18:40.000Z
2021-12-06T23:01:16.000Z
include/btle/siLabsBgApi/cxa_siLabsBgApi_btle_central.h
OpenCXA/common-c
0f7b401aff141c8b8df867f0cff5f31f6a1ee4cf
[ "MIT" ]
8
2015-07-02T00:51:53.000Z
2019-07-12T12:38:13.000Z
include/btle/siLabsBgApi/cxa_siLabsBgApi_btle_central.h
OpenCXA/common-c
0f7b401aff141c8b8df867f0cff5f31f6a1ee4cf
[ "MIT" ]
3
2017-01-13T18:04:51.000Z
2019-08-14T20:58:20.000Z
/* * This file is subject to the terms and conditions defined in * file 'LICENSE', which is part of this source code package. * * @author Christopher Armenio */ #ifndef CXA_SILABSBGAPI_BTLE_CENTRAL_H_ #define CXA_SILABSBGAPI_BTLE_CENTRAL_H_ // ******** includes ******** #include <cxa_config.h> #if defined(CXA_SILABSBGAPI_MODE_SOC) || defined(CXA_SILABSBGAPI_MODE_SOC_HIGH_POWER) #include "bg_types.h" #include "native_gecko.h" #include "infrastructure.h" #else #include <gecko_bglib.h> #endif #include <cxa_btle_central.h> #include <cxa_btle_uuid.h> #include <cxa_eui48.h> #include <cxa_ioStream_peekable.h> #include <cxa_siLabsBgApi_btle_connection.h> // ******** global macro definitions ******** #ifndef CXA_SILABSBGAPI_BTLE_CENTRAL_MAXNUM_CONNS #define CXA_SILABSBGAPI_BTLE_CENTRAL_MAXNUM_CONNS 2 #endif // ******** global type definitions ********* /** * @public */ typedef struct cxa_siLabsBgApi_btle_central cxa_siLabsBgApi_btle_central_t; /** * @private */ struct cxa_siLabsBgApi_btle_central { cxa_btle_central_t super; int threadId; bool isConnectionInProgress; cxa_siLabsBgApi_btle_connection_t conns[CXA_SILABSBGAPI_BTLE_CENTRAL_MAXNUM_CONNS]; }; // ******** global function prototypes ******** /** * @protected */ void cxa_siLabsBgApi_btle_central_init(cxa_siLabsBgApi_btle_central_t *const btlecIn, int threadIdIn); /** * @public */ bool cxa_siLabsBgApi_btle_central_setConnectionInterval(cxa_siLabsBgApi_btle_central_t *const btlecIn, cxa_eui48_t *const targetConnectionAddressIn, uint16_t connectionInterval_msIn); /** * @protected * * @return true if this event was handled */ bool cxa_siLabsBgApi_btle_central_handleBgEvent(cxa_siLabsBgApi_btle_central_t *const btlecIn, struct gecko_cmd_packet *evt); #endif
23.051948
183
0.769577
6903d915946c8bada635e57a218d5fae745b1c3b
491
c
C
tiger/parsetest.c
yufeiminds/tiger
cde8060d250c85b9f02e09ec48a7f86f087c65aa
[ "MIT" ]
8
2019-01-28T16:31:35.000Z
2021-06-28T11:58:31.000Z
tiger/parsetest.c
yufeiminds/tiger
cde8060d250c85b9f02e09ec48a7f86f087c65aa
[ "MIT" ]
null
null
null
tiger/parsetest.c
yufeiminds/tiger
cde8060d250c85b9f02e09ec48a7f86f087c65aa
[ "MIT" ]
2
2020-02-20T03:01:39.000Z
2022-03-22T00:29:26.000Z
#include <stdio.h> #include "util.h" #include "absyn.h" #include "prabsyn.h" #include "errormsg.h" extern int yyparse(void); extern A_exp absyn_root; void parse(string fname) {EM_reset(fname); if (yyparse() == 0) /* parsing worked */ fprintf(stdout,"Parsing successful!\n"); else fprintf(stdout,"Parsing failed\n"); } int main(int argc, char **argv) { if (argc!=2) {fprintf(stderr,"usage: a.out filename\n"); exit(1);} parse(argv[1]); pr_exp(stdout, absyn_root, 4); return 0; }
20.458333
67
0.678208
69190743be2364176253d84485ddfdba52f2103c
285
h
C
InjectionIII/HelperProxy.h
ljh740/InjectionIII
8b3bf118fa086bfdc5637a163c1c814a1a8ab765
[ "MIT" ]
2,848
2017-11-18T08:59:37.000Z
2022-03-31T08:11:48.000Z
InjectionIII/HelperProxy.h
ilfocus/InjectionIII
a7ea31d21d1d059107bd7a2f43a8f8a65c41a451
[ "MIT" ]
312
2017-11-21T22:48:25.000Z
2022-03-24T10:28:00.000Z
InjectionIII/HelperProxy.h
ilfocus/InjectionIII
a7ea31d21d1d059107bd7a2f43a8f8a65c41a451
[ "MIT" ]
258
2017-11-22T02:14:32.000Z
2022-03-25T11:18:05.000Z
// // HelperProxy.h // Smuggler // // Created by John Holdsworth on 24/06/2016. // Copyright © 2016 John Holdsworth. All rights reserved. // #import <Foundation/Foundation.h> @interface HelperProxy : NSObject + (BOOL)inject:(NSString *)bundlePath error:(NSError **)error; @end
17.8125
62
0.701754
5014cb8c79abd7a2fda494076af9c3b61c0fd3bf
22,053
c
C
windows/appcompat/tools/acbrowser/acbrowser.c
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
windows/appcompat/tools/acbrowser/acbrowser.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
windows/appcompat/tools/acbrowser/acbrowser.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
#include "acBrowser.h" #include "resource.h" #include <commctrl.h> #include <commdlg.h> #include <stdlib.h> #include <stdio.h> #include <stdarg.h> extern PDBENTRY g_pEntries; #define SHOW_W_SHIMS 0x00000001 #define SHOW_W_FLAGS 0x00000002 #define SHOW_W_LAYERS 0x00000004 #define SHOW_W_PATCHES 0x00000008 #define SHOW_W_APPHELP 0x00000010 #define SHOW_WO_SHIMS 0x00000100 #define SHOW_WO_FLAGS 0x00000200 #define SHOW_WO_LAYERS 0x00000400 #define SHOW_WO_PATCHES 0x00000800 #define SHOW_WO_APPHELP 0x00001000 // // These flags cannot occur simultaneously. // #define SHOW_MORETHAN5 0x00010000 #define SHOW_NOMATCHING 0x00020000 #define SHOW_DISABLED_ONLY 0x80000000 #define ID_SHOW_CONTENT 1234 // // Global Variables // HINSTANCE g_hInstance; HWND g_hDlg; HWND g_hwndList; HWND g_hwndEntryTree; int g_nItems; BOOL g_bSortAppAsc; BOOL g_bSortExeAsc; PDBENTRY g_pSelEntry; char g_szBinary[MAX_PATH]; DWORD g_dwCrtShowFlags = 0xFFFFFFFF; #define COLUMN_APP 0 #define COLUMN_EXE 1 char* g_szSeverity[] = { "NONE", "NOBLOCK", "HARDBLOCK", "MINORPROBLEM", "REINSTALL", "VERSIONSUB", "SHIM"}; #define IDQ_ALL 0 #define IDQ_MORETHAN5 1 #define IDQ_NOMATCHING 2 char* g_aszQueries[] = { "All entries", "Entries with more than 5 extra matching files", "Entries with no extra matching files", "" }; void LogMsg( LPSTR pszFmt, ... ) { CHAR gszT[1024]; va_list arglist; va_start(arglist, pszFmt); _vsnprintf(gszT, 1023, pszFmt, arglist); gszT[1023] = 0; va_end(arglist); OutputDebugString(gszT); } /******************************************************************************* * CenterWindow * * This function must be called at the WM_INIDIALOG in order to * move the dialog window centered in the client area of the * parent or owner window. *******************************************************************************/ BOOL CenterWindow( HWND hWnd) { RECT rectWindow, rectParent, rectScreen; int nCX, nCY; HWND hParent; POINT ptPoint; hParent = GetParent(hWnd); if (hParent == NULL) hParent = GetDesktopWindow(); GetWindowRect(hParent, (LPRECT)&rectParent); GetWindowRect(hWnd, (LPRECT)&rectWindow); GetWindowRect(GetDesktopWindow(), (LPRECT)&rectScreen); nCX = rectWindow.right - rectWindow.left; nCY = rectWindow.bottom - rectWindow.top; ptPoint.x = ((rectParent.right + rectParent.left) / 2) - (nCX / 2); ptPoint.y = ((rectParent.bottom + rectParent.top ) / 2) - (nCY / 2); if (ptPoint.x < rectScreen.left) ptPoint.x = rectScreen.left; if (ptPoint.x > rectScreen.right - nCX) ptPoint.x = rectScreen.right - nCX; if (ptPoint.y < rectScreen.top) ptPoint.y = rectScreen.top; if (ptPoint.y > rectScreen.bottom - nCY) ptPoint.y = rectScreen.bottom - nCY; if (GetWindowLong(hWnd, GWL_STYLE) & WS_CHILD) ScreenToClient(hParent, (LPPOINT)&ptPoint); if (!MoveWindow(hWnd, ptPoint.x, ptPoint.y, nCX, nCY, TRUE)) return FALSE; return TRUE; } void AddEntryToList( PDBENTRY pEntry ) { LVITEM lvi; lvi.mask = LVIF_TEXT | LVIF_PARAM; lvi.pszText = pEntry->pszAppName; lvi.iItem = g_nItems; lvi.iSubItem = COLUMN_APP; lvi.lParam = (LPARAM)pEntry; ListView_InsertItem(g_hwndList, &lvi); ListView_SetItemText(g_hwndList, g_nItems, COLUMN_EXE, pEntry->pszExeName); g_nItems++; } void InsertColumnIntoListView( LPSTR lpszColumn, DWORD dwSubItem, DWORD widthPercent ) { LVCOLUMN lvc; RECT rcClient; DWORD width; GetWindowRect(g_hwndList, &rcClient); width = rcClient.right - rcClient.left - 4 * GetSystemMetrics(SM_CXBORDER) - GetSystemMetrics(SM_CXVSCROLL); width = width * widthPercent / 100; lvc.mask = LVCF_FMT | LVCF_TEXT | LVCF_SUBITEM | LVCF_WIDTH; lvc.fmt = LVCFMT_LEFT; lvc.iSubItem = dwSubItem; lvc.cx = width; lvc.pszText = lpszColumn; ListView_InsertColumn(g_hwndList, dwSubItem, &lvc); } void UpdateEntryTreeView( PDBENTRY pEntry ) { HTREEITEM hItemExe; HTREEITEM hMatchItem; HTREEITEM hItemMatchingFiles; PMATCHINGFILE pMatch; PFIXLIST pFixList; TV_INSERTSTRUCT is; char szText[256]; TreeView_DeleteAllItems(g_hwndEntryTree); wsprintf(szText, "%s - %s", pEntry->pszExeName, pEntry->szGUID); is.hParent = TVI_ROOT; is.hInsertAfter = TVI_LAST; is.item.mask = TVIF_TEXT | TVIF_PARAM; is.item.lParam = 0; is.item.pszText = szText; hItemExe = TreeView_InsertItem(g_hwndEntryTree, &is); if (pEntry->appHelp.bPresent) { wsprintf(szText, "AppHelp - %s", g_szSeverity[pEntry->appHelp.severity]); is.hParent = hItemExe; is.item.pszText = szText; TreeView_InsertItem(g_hwndEntryTree, &is); } if (pEntry->pFirstShim) { HTREEITEM hItemShims; is.hParent = hItemExe; is.hInsertAfter = TVI_SORT; is.item.lParam = 0; is.item.pszText = "Compatibility Fixes"; hItemShims = TreeView_InsertItem(g_hwndEntryTree, &is); is.hParent = hItemShims; pFixList = pEntry->pFirstShim; while (pFixList) { is.item.lParam = (LPARAM)pFixList->pFix->pszDescription; is.item.pszText = pFixList->pFix->pszName; TreeView_InsertItem(g_hwndEntryTree, &is); pFixList = pFixList->pNext; } TreeView_Expand(g_hwndEntryTree, hItemShims, TVE_EXPAND); } if (pEntry->pFirstPatch) { HTREEITEM hItemPatches; is.hParent = hItemExe; is.hInsertAfter = TVI_SORT; is.item.lParam = 0; is.item.pszText = "Compatibility Patches"; hItemPatches = TreeView_InsertItem(g_hwndEntryTree, &is); is.hParent = hItemPatches; pFixList = pEntry->pFirstPatch; while (pFixList) { is.item.lParam = (LPARAM)pFixList->pFix->pszDescription; is.item.pszText = pFixList->pFix->pszName; TreeView_InsertItem(g_hwndEntryTree, &is); pFixList = pFixList->pNext; } TreeView_Expand(g_hwndEntryTree, hItemPatches, TVE_EXPAND); } if (pEntry->pFirstFlag) { HTREEITEM hItemFlags; is.hParent = hItemExe; is.hInsertAfter = TVI_SORT; is.item.lParam = 0; is.item.pszText = "Compatibility Flags"; hItemFlags = TreeView_InsertItem(g_hwndEntryTree, &is); is.hParent = hItemFlags; pFixList = pEntry->pFirstFlag; while (pFixList) { is.item.lParam = (LPARAM)pFixList->pFix->pszDescription; is.item.pszText = pFixList->pFix->pszName; TreeView_InsertItem(g_hwndEntryTree, &is); pFixList = pFixList->pNext; } TreeView_Expand(g_hwndEntryTree, hItemFlags, TVE_EXPAND); } if (pEntry->pFirstLayer) { HTREEITEM hItemLayers; is.hParent = hItemExe; is.hInsertAfter = TVI_SORT; is.item.lParam = 0; is.item.pszText = "Compatibility Layers"; hItemLayers = TreeView_InsertItem(g_hwndEntryTree, &is); is.hParent = hItemLayers; pFixList = pEntry->pFirstLayer; while (pFixList) { is.item.lParam = (LPARAM)pFixList->pFix->pszDescription; is.item.pszText = pFixList->pFix->pszName; TreeView_InsertItem(g_hwndEntryTree, &is); pFixList = pFixList->pNext; } TreeView_Expand(g_hwndEntryTree, hItemLayers, TVE_EXPAND); } pMatch = pEntry->pFirstMatchingFile; is.hParent = hItemExe; is.item.lParam = 0; is.item.pszText = "Matching Files"; hItemMatchingFiles = TreeView_InsertItem(g_hwndEntryTree, &is); while (pMatch) { PATTRIBUTE pAttr; is.hInsertAfter = TVI_SORT; is.hParent = hItemMatchingFiles; is.item.pszText = pMatch->pszName; hMatchItem = TreeView_InsertItem(g_hwndEntryTree, &is); pAttr = pMatch->pFirstAttribute; while (pAttr) { is.hParent = hMatchItem; is.hInsertAfter = TVI_SORT; is.item.pszText = pAttr->pszText; TreeView_InsertItem(g_hwndEntryTree, &is); pAttr = pAttr->pNext; } pMatch = pMatch->pNext; } TreeView_Expand(g_hwndEntryTree, hItemMatchingFiles, TVE_EXPAND); TreeView_Expand(g_hwndEntryTree, hItemExe, TVE_EXPAND); } void AppSelectedChanged( HWND hdlg, int nSel ) { LVITEM lvi; PDBENTRY pEntry; if (nSel == -1) return; lvi.iItem = nSel; lvi.iSubItem = 0; lvi.mask = LVIF_PARAM; ListView_GetItem(g_hwndList, &lvi); pEntry = (PDBENTRY)lvi.lParam; g_pSelEntry = pEntry; // // Update the entry tree view // UpdateEntryTreeView(pEntry); SendDlgItemMessage(hdlg, IDC_PER_USER, BM_SETCHECK, (pEntry->bDisablePerUser ? BST_CHECKED : BST_UNCHECKED), 0); SendDlgItemMessage(hdlg, IDC_PER_MACHINE, BM_SETCHECK, (pEntry->bDisablePerMachine ? BST_CHECKED : BST_UNCHECKED), 0); } int CALLBACK CompareItems( LPARAM lParam1, LPARAM lParam2, LPARAM column) { PDBENTRY pItem1 = (PDBENTRY)lParam1; PDBENTRY pItem2 = (PDBENTRY)lParam2; int nVal = 0; if (column == COLUMN_APP) { if (g_bSortAppAsc) { nVal = lstrcmpi(pItem1->pszAppName, pItem2->pszAppName); } else { nVal = lstrcmpi(pItem2->pszAppName, pItem1->pszAppName); } } if (column == COLUMN_EXE) { if (g_bSortExeAsc) { nVal = lstrcmpi(pItem1->pszExeName, pItem2->pszExeName); } else { nVal = lstrcmpi(pItem2->pszExeName, pItem1->pszExeName); } } return nVal; } void ShowFixes( HWND hdlg, DWORD dwShowFlags ) { PDBENTRY pEntry; char szEntries[128]; BOOL bDontShow; if (dwShowFlags == g_dwCrtShowFlags) { return; } g_nItems = 0; SendMessage(g_hwndList, WM_SETREDRAW, FALSE, 0); ListView_DeleteAllItems(g_hwndList); pEntry = g_pEntries; while (pEntry != NULL) { bDontShow = (pEntry->pFirstShim == NULL && (dwShowFlags & SHOW_W_SHIMS) || pEntry->appHelp.bPresent == FALSE && (dwShowFlags & SHOW_W_APPHELP) || pEntry->pFirstFlag == NULL && (dwShowFlags & SHOW_W_FLAGS) || pEntry->pFirstPatch == NULL && (dwShowFlags & SHOW_W_PATCHES) || pEntry->pFirstLayer == NULL && (dwShowFlags & SHOW_W_LAYERS)); bDontShow = bDontShow || (pEntry->pFirstShim && (dwShowFlags & SHOW_WO_SHIMS) || pEntry->appHelp.bPresent && (dwShowFlags & SHOW_WO_APPHELP) || pEntry->pFirstFlag && (dwShowFlags & SHOW_WO_FLAGS) || pEntry->pFirstPatch && (dwShowFlags & SHOW_WO_PATCHES) || pEntry->pFirstLayer && (dwShowFlags & SHOW_WO_LAYERS)); if ((dwShowFlags & SHOW_DISABLED_ONLY) && !pEntry->bDisablePerMachine && !pEntry->bDisablePerUser) { bDontShow = TRUE; } if (dwShowFlags & SHOW_MORETHAN5) { if (pEntry->nMatchingFiles < 6) { bDontShow = TRUE; } } if (dwShowFlags & SHOW_NOMATCHING) { if (pEntry->nMatchingFiles > 1) { bDontShow = TRUE; } } if (!bDontShow) { AddEntryToList(pEntry); } pEntry = pEntry->pNext; } ListView_SortItems(g_hwndList, CompareItems, COLUMN_APP); wsprintf(szEntries, "%d entries. Use the headers to sort them.", g_nItems); SetDlgItemText(hdlg, IDC_ALL_ENTRIES, szEntries); SendMessage(g_hwndList, WM_SETREDRAW, TRUE, 0); g_dwCrtShowFlags = dwShowFlags; } void DoInitDialog( HWND hdlg ) { HICON hIcon; int i; g_hDlg = hdlg; CenterWindow(hdlg); g_hwndList = GetDlgItem(hdlg, IDC_LIST); ListView_SetExtendedListViewStyle(g_hwndList, 0x20); g_hwndEntryTree = GetDlgItem(hdlg, IDC_ENTRY); g_nItems = 0; InsertColumnIntoListView("Application", COLUMN_APP, 60); InsertColumnIntoListView("Main Binary", COLUMN_EXE, 40); g_bSortAppAsc = TRUE; g_bSortExeAsc = FALSE; // // Show the app icon. // hIcon = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_APPICON)); SetClassLongPtr(hdlg, GCLP_HICON, (LONG_PTR)hIcon); SendDlgItemMessage(hdlg, IDC_DC_APPHELP, BM_SETCHECK, BST_CHECKED, 0); SendDlgItemMessage(hdlg, IDC_DC_SHIMS, BM_SETCHECK, BST_CHECKED, 0); SendDlgItemMessage(hdlg, IDC_DC_FLAGS, BM_SETCHECK, BST_CHECKED, 0); SendDlgItemMessage(hdlg, IDC_DC_PATCHES, BM_SETCHECK, BST_CHECKED, 0); SendDlgItemMessage(hdlg, IDC_DC_LAYERS, BM_SETCHECK, BST_CHECKED, 0); // // Populate the statistics queries // for (i = 0; *g_aszQueries[i] != 0; i++) { SendDlgItemMessage(hdlg, IDC_STATISTICS, CB_ADDSTRING, 0, (LPARAM)g_aszQueries[i]); } SetCursor(NULL); SetTimer(hdlg, ID_SHOW_CONTENT, 100, NULL); } void FilterAndShow( HWND hdlg ) { DWORD dwShowFlags = 0; if (SendDlgItemMessage(hdlg, IDC_W_APPHELP, BM_GETCHECK, 0, 0) == BST_CHECKED) { dwShowFlags |= SHOW_W_APPHELP; } else if (SendDlgItemMessage(hdlg, IDC_WO_APPHELP, BM_GETCHECK, 0, 0) == BST_CHECKED) { dwShowFlags |= SHOW_WO_APPHELP; } if (SendDlgItemMessage(hdlg, IDC_W_SHIMS, BM_GETCHECK, 0, 0) == BST_CHECKED) { dwShowFlags |= SHOW_W_SHIMS; } else if (SendDlgItemMessage(hdlg, IDC_WO_SHIMS, BM_GETCHECK, 0, 0) == BST_CHECKED) { dwShowFlags |= SHOW_WO_SHIMS; } if (SendDlgItemMessage(hdlg, IDC_W_PATCHES, BM_GETCHECK, 0, 0) == BST_CHECKED) { dwShowFlags |= SHOW_W_PATCHES; } else if (SendDlgItemMessage(hdlg, IDC_WO_PATCHES, BM_GETCHECK, 0, 0) == BST_CHECKED) { dwShowFlags |= SHOW_WO_PATCHES; } if (SendDlgItemMessage(hdlg, IDC_W_FLAGS, BM_GETCHECK, 0, 0) == BST_CHECKED) { dwShowFlags |= SHOW_W_FLAGS; } else if (SendDlgItemMessage(hdlg, IDC_WO_FLAGS, BM_GETCHECK, 0, 0) == BST_CHECKED) { dwShowFlags |= SHOW_WO_FLAGS; } if (SendDlgItemMessage(hdlg, IDC_W_LAYERS, BM_GETCHECK, 0, 0) == BST_CHECKED) { dwShowFlags |= SHOW_W_LAYERS; } else if (SendDlgItemMessage(hdlg, IDC_WO_LAYERS, BM_GETCHECK, 0, 0) == BST_CHECKED) { dwShowFlags |= SHOW_WO_LAYERS; } if (SendDlgItemMessage(hdlg, IDC_DISABLED_ONLY, BM_GETCHECK, 0, 0) == BST_CHECKED) { dwShowFlags |= SHOW_DISABLED_ONLY; } SendDlgItemMessage(hdlg, IDC_PER_USER, BM_SETCHECK, BST_UNCHECKED, 0); SendDlgItemMessage(hdlg, IDC_PER_MACHINE, BM_SETCHECK, BST_UNCHECKED, 0); ShowFixes(hdlg, dwShowFlags); TreeView_DeleteAllItems(g_hwndEntryTree); } void OnSubmitChanges( HWND hdlg ) { BOOL bPerUser, bPerMachine; if (g_pSelEntry == NULL) { return; } bPerUser = (SendDlgItemMessage(hdlg, IDC_PER_USER, BM_GETCHECK, 0, 0) == BST_CHECKED); bPerMachine = (SendDlgItemMessage(hdlg, IDC_PER_MACHINE, BM_GETCHECK, 0, 0) == BST_CHECKED); UpdateFixStatus(g_pSelEntry->szGUID, bPerUser, bPerMachine); g_pSelEntry->bDisablePerUser = bPerUser; g_pSelEntry->bDisablePerMachine = bPerMachine; } INT_PTR CALLBACK BrowseAppCompatDlgProc( HWND hdlg, UINT uMsg, WPARAM wParam, LPARAM lParam ) { int wCode = LOWORD(wParam); int wNotifyCode = HIWORD(wParam); switch (uMsg) { case WM_INITDIALOG: DoInitDialog(hdlg); break; case WM_TIMER: if (wParam == ID_SHOW_CONTENT) { KillTimer(hdlg, ID_SHOW_CONTENT); // // Read the database // GetDatabaseEntries(); ShowFixes(hdlg, 0); SetCursor(LoadCursor(NULL, MAKEINTRESOURCE(IDC_ARROW))); } break; case WM_NOTIFY: if (wParam == IDC_LIST) { LPNMHDR pnm = (LPNMHDR)lParam; switch (pnm->code) { case LVN_COLUMNCLICK: { LPNMLISTVIEW pnmlv = (LPNMLISTVIEW)lParam; if (pnmlv->iSubItem == COLUMN_APP) { g_bSortAppAsc = !g_bSortAppAsc; } if (pnmlv->iSubItem == COLUMN_EXE) { g_bSortExeAsc = !g_bSortExeAsc; } ListView_SortItems(g_hwndList, CompareItems, pnmlv->iSubItem); break; } case LVN_ITEMCHANGED: { int nSel = ListView_GetSelectionMark(g_hwndList); AppSelectedChanged(hdlg, nSel); break; } case NM_CLICK: { LVHITTESTINFO ht; int nSel; GetCursorPos(&ht.pt); ScreenToClient(g_hwndList, &ht.pt); nSel = ListView_SubItemHitTest(g_hwndList, &ht); if (nSel != -1) { ListView_SetItemState(g_hwndList, nSel, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED); } AppSelectedChanged(hdlg, nSel); break; } default: break; } } else if (wParam == IDC_ENTRY) { LPNMHDR pnm = (LPNMHDR)lParam; switch (pnm->code) { case TVN_GETINFOTIP: { LPNMTVGETINFOTIP lpGetInfoTip = (LPNMTVGETINFOTIP)lParam; if (lpGetInfoTip->lParam != 0) { lstrcpy(lpGetInfoTip->pszText, (char*)lpGetInfoTip->lParam); } break; } } } break; case WM_COMMAND: if (wNotifyCode == CBN_SELCHANGE) { int nSel; nSel = (int)SendDlgItemMessage(hdlg, IDC_STATISTICS, CB_GETCURSEL, 0, 0); switch (nSel) { case IDQ_ALL: ShowFixes(hdlg, (g_dwCrtShowFlags & ~(SHOW_MORETHAN5 | SHOW_NOMATCHING))); break; case IDQ_MORETHAN5: ShowFixes(hdlg, ((g_dwCrtShowFlags | SHOW_MORETHAN5) & ~SHOW_NOMATCHING)); break; case IDQ_NOMATCHING: ShowFixes(hdlg, ((g_dwCrtShowFlags | SHOW_NOMATCHING) & ~SHOW_MORETHAN5)); break; } } switch (wCode) { case IDC_PER_USER: case IDC_PER_MACHINE: OnSubmitChanges(hdlg); break; case IDC_W_APPHELP: case IDC_W_SHIMS: case IDC_W_FLAGS: case IDC_W_LAYERS: case IDC_W_PATCHES: case IDC_WO_APPHELP: case IDC_WO_SHIMS: case IDC_WO_FLAGS: case IDC_WO_LAYERS: case IDC_WO_PATCHES: case IDC_DC_APPHELP: case IDC_DC_SHIMS: case IDC_DC_FLAGS: case IDC_DC_LAYERS: case IDC_DC_PATCHES: case IDC_DISABLED_ONLY: FilterAndShow(hdlg); break; case IDCANCEL: EndDialog(hdlg, TRUE); break; default: return FALSE; } break; default: return FALSE; } return TRUE; } int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { InitCommonControls(); g_hInstance = hInstance; DialogBox(hInstance, MAKEINTRESOURCE(IDD_DIALOG), GetDesktopWindow(), BrowseAppCompatDlgProc); return 0; }
26.992656
97
0.5436
fb0be8d6560c95e572359d1e334ca76ebed8c4bd
4,545
c
C
draw/draw.c
mplv/crl
3c7eccbd33d8498483185af8adaee442f10d7558
[ "BSD-3-Clause" ]
null
null
null
draw/draw.c
mplv/crl
3c7eccbd33d8498483185af8adaee442f10d7558
[ "BSD-3-Clause" ]
null
null
null
draw/draw.c
mplv/crl
3c7eccbd33d8498483185af8adaee442f10d7558
[ "BSD-3-Clause" ]
null
null
null
#include "draw.h" #include <SDL2/SDL.h> #include "entity/creature/creature.h" #include "textures/textures.h" #include "runtimecontext/runtimecontext.h" /* For testing that the sprite sheet works with the enum */ /* void RL_Draw(RL_RTContext *rtc, SDL_Renderer *renderer) { texture_id_type i = SPACE; int x = 0,y = 0; SDL_Texture *tex = NULL; SDL_Rect dstRect = {x:0,y:0,w:rtc->conf->tileWidth,h:rtc->conf->tileHeight}; for (; i < 87; i++) { if (x > rtc->conf->widthToTiles - 1) { x = 0; y++; } dstRect.x = x*64; dstRect.y = y*64; printf("Getting %d at (%d,%d)\n", i,dstRect.x, dstRect.y); tex = Textures_Get(rtc->textures,i); if (tex == NULL) { printf("Texture %d not availible\n", i); break; } SDL_SetTextureColorMod(tex,255,255,255); SDL_RenderCopy(renderer,tex,NULL,&dstRect); x++; } printf("%d\n", O); }*/ void RL_Draw(RL_RTContext *rtc, SDL_Renderer *renderer) { int cx = 0; int cy = 0; // Calculate the top left x position of the camera if (rtc->player->ent->x < (rtc->conf->widthToTiles / 2)) { cx = 0; } else if (rtc->player->ent->x > rtc->conf->mapsizex - (rtc->conf->widthToTiles / 2)) { cx = rtc->conf->mapsizex - rtc->conf->widthToTiles; } else { cx = rtc->player->ent->x - (rtc->conf->widthToTiles / 2); } // same with the y pos if (rtc->player->ent->y < (rtc->conf->heightToTiles / 2)) { cy = 0; } else if (rtc->player->ent->y > rtc->conf->mapsizey - (rtc->conf->heightToTiles / 2)) { cy = rtc->conf->mapsizey - rtc->conf->heightToTiles; } else { cy = rtc->player->ent->y - (rtc->conf->heightToTiles / 2) - 1; } // fix the out of bounds that y gives when camera is near top // TODO should fix that if (cx < 0) cx = 0; if (cy < 0) cy = 0; // draw the map from that location SDL_Rect dstRect = {x:0, y:0, w:rtc->conf->tileWidth, h:rtc->conf->tileHeight}; SDL_Texture *tex = NULL; unsigned char rgbMod[3] = {0}; int i = 0; int j = 0; for (i = cy; i < cy+rtc->conf->heightToTiles; i++) { for (j = cx; j < cx+rtc->conf->widthToTiles; j++) { dstRect.x = j*rtc->conf->tileWidth-cx*rtc->conf->tileWidth; dstRect.y = i*rtc->conf->tileHeight-cy*rtc->conf->tileHeight; tex = Textures_Get(rtc->textures,rtc->map->map[j][i]); if (tex == NULL) { printf("Texture %d not availible\n", rtc->map->map[j][i]); break; } rtc->map->GetColor(rtc->map,rgbMod,rtc->map->map[j][i]); SDL_SetTextureColorMod(tex,rgbMod[0],rgbMod[1],rgbMod[2]); SDL_RenderCopy(renderer,tex,NULL,&dstRect); SDL_SetTextureColorMod(tex,255,255,255); } } // for _, e := range GameState.MonsterList {} int numCreatures = AL_Size(rtc->creatures); for (i = 0; i < numCreatures; i++) { // draw creatures and color them // assuming that they are visible in the camera RL_Creature* creature = AL_Get(rtc->creatures, i); if (creature->ent.x >= cx && creature->ent.x < cx+rtc->conf->widthToTiles && creature->ent.y >= cy && creature->ent.y < cy+rtc->conf->heightToTiles) { // blank out the tile behind the creature dstRect.x = (creature->ent.x - cx) * rtc->conf->tileWidth; dstRect.y = (creature->ent.y - cy) * rtc->conf->tileWidth; SDL_SetRenderDrawColor(renderer,0,0,0,255); SDL_RenderFillRect(renderer, &dstRect); // then draw the character offset by the camera // tex = textures.GetTile('@') dstRect.x = (creature->ent.x - cx) * rtc->conf->tileWidth; dstRect.y = (creature->ent.y - cy) * rtc->conf->tileWidth; tex = Textures_Get(rtc->textures,creature->ent.texture); if (tex == NULL) { printf("Texture %d not availible\n", AT); } SDL_SetTextureColorMod(tex,creature->ent.r,creature->ent.g,creature->ent.b); SDL_RenderCopy(renderer,tex,NULL,&dstRect); SDL_SetTextureColorMod(tex,255,255,255); } } // blank out the tile behind the player dstRect.x = (rtc->player->ent->x - cx) * rtc->conf->tileWidth; dstRect.y = (rtc->player->ent->y - cy) * rtc->conf->tileWidth; SDL_SetRenderDrawColor(renderer,0,0,0,255); SDL_RenderFillRect(renderer, &dstRect); // then draw the character offset by the camera // tex = textures.GetTile('@') dstRect.x = (rtc->player->ent->x - cx) * rtc->conf->tileWidth; dstRect.y = (rtc->player->ent->y - cy) * rtc->conf->tileWidth; tex = Textures_Get(rtc->textures,rtc->player->ent->texture); if (tex == NULL) { printf("Texture %d not availible\n", AT); } SDL_SetTextureColorMod(tex,rtc->player->ent->r,rtc->player->ent->g,rtc->player->ent->b); SDL_RenderCopy(renderer,tex,NULL,&dstRect); SDL_SetTextureColorMod(tex,255,255,255); }
34.172932
89
0.642904
594ad7d8b2aa7f9241d5689e6caffdd048562f1c
819
h
C
Include/algorithms/Ilona/Browerfs.h
av-elier/fast-exponentiation-algs
1d6393021583686372564a7ca52b09dc7013fb38
[ "MIT" ]
2
2016-10-17T20:30:05.000Z
2020-03-24T19:52:14.000Z
Include/algorithms/Ilona/Browerfs.h
av-elier/fast-exponentiation-algs
1d6393021583686372564a7ca52b09dc7013fb38
[ "MIT" ]
null
null
null
Include/algorithms/Ilona/Browerfs.h
av-elier/fast-exponentiation-algs
1d6393021583686372564a7ca52b09dc7013fb38
[ "MIT" ]
null
null
null
#ifndef BROWERFS_H #define BROWERFS_H #include <stdio.h> #include <NTL/ZZ_p.h> #include <NTL/ZZ.h> #include <vector> #include <map> #include <cmath> #include "ExpAlgInterfaces.h" //NTL_CLIENT namespace Ilona { class BrowerSigned: public ExpAlg { public: BrowerSigned(); ~BrowerSigned(); void precalculate(ZZ_p x, ZZ exponent); ZZ_p sum(ZZ_p a , ZZ_p b); ZZ_p product(ZZ_p a , ZZ_p b); ZZ_p square(ZZ_p a); ZZ findInvr(const ZZ& a); long long pow2( unsigned long long P); long long kcount( ZZ n , int limit , int &degree ); void dec_base( ZZ n, int base , vector<ZZ> &bin ); void CreateNAF(ZZ x); void InvNAF(ZZ n); void sigma( ZZ m , int k , int & s , ZZ & u ); ZZ_p exp(ZZ_p x,ZZ exponent); private: map<ZZ,ZZ_p> vecx; int k; vector<ZZ> bin; vector<ZZ> binN; }; } #endif
17.425532
52
0.65812
74b76e306069847b4114a7169a309414af9d4fbd
3,796
h
C
COW_UIKitHelpers.h
AmazingCow/UIKitHelpers
f19b80a0762a891ea31c8d20137afc8ef7465e90
[ "BSD-3-Clause" ]
null
null
null
COW_UIKitHelpers.h
AmazingCow/UIKitHelpers
f19b80a0762a891ea31c8d20137afc8ef7465e90
[ "BSD-3-Clause" ]
null
null
null
COW_UIKitHelpers.h
AmazingCow/UIKitHelpers
f19b80a0762a891ea31c8d20137afc8ef7465e90
[ "BSD-3-Clause" ]
null
null
null
//----------------------------------------------------------------------------// // █ █ // // ████████ // // ██ ██ // // ███ █ █ ███ COW_UIKitHelpers.h // // █ █ █ █ UIKitHelpers // // ████████████ // // █ █ Copyright (c) 2015, 2016 // // █ █ █ █ AmazingCow - www.AmazingCow.com // // █ █ █ █ // // █ █ N2OMatt - n2omatt@amazingcow.com // // ████████████ www.amazingcow.com/n2omatt // // // // This software is licensed as GPLv3 // // CHECK THE COPYING FILE TO MORE DETAILS // // // // Permission is granted to anyone to use this software for any purpose, // // including commercial applications, and to alter it and redistribute it // // freely, subject to the following restrictions: // // // // 0. You **CANNOT** change the type of the license. // // 1. The origin of this software must not be misrepresented; // // you must not claim that you wrote the original software. // // 2. If you use this software in a product, an acknowledgment in the // // product IS HIGHLY APPRECIATED, both in source and binary forms. // // (See opensource.AmazingCow.com/acknowledgment.html for details). // // If you will not acknowledge, just send us a email. We'll be // // *VERY* happy to see our work being used by other people. :) // // The email is: acknowledgment_opensource@AmazingCow.com // // 3. Altered source versions must be plainly marked as such, // // and must notbe misrepresented as being the original software. // // 4. This notice may not be removed or altered from any source // // distribution. // // 5. Most important, you must have fun. ;) // // // // Visit opensource.amazingcow.com for more open-source projects. // // // // Enjoy :) // //----------------------------------------------------------------------------// // Macros // #import "COW_UIKitHelpers_Macros.h" //This is a umbrella header for all macros. // Classes // #import "COWAlertView.h" // Categories // //NSString #import "NSString+COWWhitespaceAdditions.h" //UIButton #import "UIButton+COWBackgroundColorAdditions.h" //UIColor #import "UIColor+COWHexStringAdditions.h" //UIImage #import "UIImage+COWColorAdditions.h" #import "UIImage+COWRoundedCornerAdditions.h" #import "UIImage+COWCheckedLoad.h" //UINavigationController #import "UINavigationController+COWShadowlessNavigationBar.h" //UIView #import "UIView+COWBorderColorAdditions.h" #import "UIView+COWRoundedCornersAdditions.h"
56.656716
80
0.398314
46bf2ad060038291f125eb5a63823c9bdd494c04
3,208
h
C
grante/MultichainGibbsInference.h
pantonante/grante-bazel
e3f22ec111463a7ae0686494422ab09f86b4d39a
[ "DOC" ]
null
null
null
grante/MultichainGibbsInference.h
pantonante/grante-bazel
e3f22ec111463a7ae0686494422ab09f86b4d39a
[ "DOC" ]
null
null
null
grante/MultichainGibbsInference.h
pantonante/grante-bazel
e3f22ec111463a7ae0686494422ab09f86b4d39a
[ "DOC" ]
null
null
null
#ifndef GRANTE_MCHAINGIBBSINFERENCE_H #define GRANTE_MCHAINGIBBSINFERENCE_H #include "FactorGraph.h" #include "InferenceMethod.h" #include "GibbsSampler.h" namespace Grante { /* Gibbs sampling inference with multiple chains and convergence diagnostics. * * References * * [Brooks1998], Stephen P. Brooks, Andrew Gelman, * "General Methods for Monitoring Convergence of Iterative Simulations", * Journal of Computational and Graphical Statistics, * Vol. 7, No. 4, pages 434--455, December 1998. * * [Gelman1992], Andrew Gelman, Donald B. Rubin, * "Inference from Iterative Simulation using Multiple Sequences", * Statistical Science, * Vol. 7, pages 457--511, 1992. */ class MultichainGibbsInference : public InferenceMethod { public: explicit MultichainGibbsInference(const FactorGraph* fg); virtual ~MultichainGibbsInference(); virtual InferenceMethod* Produce(const FactorGraph* fg) const; // Set multi-chain Gibbs sampling parameters. // // number_of_chains: >=3, number of parallel chains used. // accept_psrf: >1.0, potential scale reduction factor acceptance // threshold; if max_i PSRF_c <= accept_psnr, then we assume the chains // have converged. // spacing_sweeps: number of sweeps to discard between samples. // Default: 0. // sample_count: number of samples used to estimate marginals after // convergence has been determined. Default: 10000. void SetSamplingParameters(unsigned int number_of_chains, double accept_psrf, unsigned int spacing_sweeps, unsigned int sample_count); // Perform Gibbs sampling to compute marginals. virtual void PerformInference(); virtual void ClearInferenceResult(); // Approximate marginals virtual const std::vector<double>& Marginal(unsigned int factor_id) const; virtual const std::vector<std::vector<double> >& Marginals() const; // Gibbs sampling does not support computation of the log-partition // function. // This method always returns the signaling_NaN value. virtual double LogPartitionFunction() const; // Produce approximate samples from the distribution virtual void Sample(std::vector<std::vector<unsigned int> >& states, unsigned int sample_count); // NOT IMPLEMENTED virtual double MinimizeEnergy(std::vector<unsigned int>& state); private: // Marginal distribution means and variances for M chains typedef std::vector<std::vector<double> > marginals_t; std::vector<marginals_t> chain_mean; std::vector<marginals_t> chain_varm; // Inference result: estimated marginal distributions for all factors std::vector<std::vector<double> > marginals; // Inference result: estimated log-partition function. // XXX: Not available through Gibbs sampling double log_z; // Workhorse: the actual Gibbs sampler used std::vector<GibbsSampler> chain_gibbs; // Gibbs sampling parameters unsigned int number_of_chains; double accept_psrf; unsigned int spacing_sweeps; unsigned int sample_count; void PerformBurninPhase(); // Setup chain_mean and chain_varm void SetupChains(void); void UpdateMeanVariance(const GibbsSampler& gibbs, marginals_t& mean, marginals_t& varm, unsigned int n); double ComputePSRF(unsigned int n) const; }; } #endif
31.762376
78
0.761534
de099c601bf62aa1f8fe0b988dd94e454abfe906
11,256
c
C
metapixel/library.c
alastorid/mystuff
ebdfb3785c3ba3348c25c21fd2d4d12c31f533e3
[ "BSD-3-Clause" ]
null
null
null
metapixel/library.c
alastorid/mystuff
ebdfb3785c3ba3348c25c21fd2d4d12c31f533e3
[ "BSD-3-Clause" ]
null
null
null
metapixel/library.c
alastorid/mystuff
ebdfb3785c3ba3348c25c21fd2d4d12c31f533e3
[ "BSD-3-Clause" ]
null
null
null
/* * library.c * * metapixel * * Copyright (C) 1997-2009 Mark Probst * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <assert.h> #include "lispreader/lispreader.h" #include "api.h" static char* tables_filename (const char *path) { char *name = (char*)malloc(strlen(path) + 1 + strlen(TABLES_FILENAME) + 1); assert(name != 0); strcpy(name, path); strcat(name, "/"); strcat(name, TABLES_FILENAME); return name; } static library_t* make_library (const char *path) { library_t *library = (library_t*)malloc(sizeof(library_t)); assert(library != 0); library->path = strdup(path); assert(library->path != 0); library->metapixels = 0; library->num_metapixels = 0; return library; } static metapixel_t* copy_metapixel_for_library (metapixel_t *metapixel, library_t *library, const char *filename) { metapixel_t *copy = (metapixel_t*)malloc(sizeof(metapixel_t)); assert(copy != 0); memcpy(copy, metapixel, sizeof(metapixel_t)); copy->library = library; copy->name = strdup(metapixel->name); copy->filename = strdup(filename); assert(copy->filename != 0); copy->bitmap = 0; copy->next = 0; return copy; } static void free_metapixels (metapixel_t *metapixel) { while (metapixel != 0) { metapixel_t *next = metapixel->next; metapixel_free(metapixel); metapixel = next; } } static void write_metapixel_metadata (metapixel_t *metapixel, FILE *out) { int channel; /* FIXME: handle write errors */ lisp_print_open_paren(out); lisp_print_symbol("small-image", out); lisp_print_string(metapixel->name, out); lisp_print_string(metapixel->filename, out); lisp_print_open_paren(out); lisp_print_symbol("size", out); lisp_print_integer(metapixel->width, out); lisp_print_integer(metapixel->height, out); lisp_print_real(metapixel->aspect_ratio, out); lisp_print_close_paren(out); lisp_print_open_paren(out); lisp_print_symbol("flip", out); lisp_print_boolean(metapixel->flip & FLIP_HOR, out); lisp_print_boolean(metapixel->flip & FLIP_VER, out); lisp_print_close_paren(out); lisp_print_open_paren(out); lisp_print_symbol("subpixel", out); for (channel = 0; channel < NUM_CHANNELS; ++channel) { static char *channel_names[] = { "r", "g", "b" }; int i; lisp_print_open_paren(out); lisp_print_symbol(channel_names[channel], out); for (i = 0; i < NUM_SUBPIXELS; ++i) lisp_print_integer((int)metapixel->subpixels_rgb[i * NUM_CHANNELS + channel], out); lisp_print_close_paren(out); } lisp_print_close_paren(out); lisp_print_open_paren(out); lisp_print_symbol("anti", out); lisp_print_integer(metapixel->anti_x, out); lisp_print_integer(metapixel->anti_y, out); lisp_print_close_paren(out); lisp_print_close_paren(out); fputs("\n", out); } static int read_tables (const char *library_dir, library_t *library) { lisp_object_t *pattern; lisp_object_t *obj; lisp_stream_t stream; int num_subs; pools_t pools; allocator_t allocator; char *tables_name; int retval = 1; assert(library != 0); assert(library->metapixels == 0); tables_name = tables_filename(library_dir); if (lisp_stream_init_path(&stream, tables_name) == 0) { error_info_t info = error_make_string_info(tables_name); free(tables_name); error_report(ERROR_TABLES_FILE_CANNOT_OPEN, info); return 0; } free(tables_name); pattern = lisp_read_from_string("(small-image #?(string) #?(string)" " (size #?(integer) #?(integer) #?(real))" " (flip #?(boolean) #?(boolean))" " (subpixel (r . #?(list)) (g . #?(list)) (b . #?(list)))" " (anti #?(integer) #?(integer)))"); assert(pattern != 0 && lisp_type(pattern) != LISP_TYPE_EOF && lisp_type(pattern) != LISP_TYPE_PARSE_ERROR); assert(lisp_compile_pattern(&pattern, &num_subs)); assert(num_subs == 12); init_pools(&pools); init_pools_allocator(&allocator, &pools); for (;;) { int type; reset_pools(&pools); obj = lisp_read_with_allocator(&allocator, &stream); type = lisp_type(obj); if (type != LISP_TYPE_EOF && type != LISP_TYPE_PARSE_ERROR) { lisp_object_t *vars[12]; if (lisp_match_pattern(pattern, obj, vars, num_subs)) { metapixel_t *pixel; lisp_object_t *lst; int channel, i; pixel = metapixel_new(lisp_string(vars[0]), lisp_integer(vars[2]), lisp_integer(vars[3]), lisp_real(vars[4])); assert(pixel != 0); pixel->filename = strdup(lisp_string(vars[1])); assert(pixel->filename != 0); pixel->anti_x = lisp_integer(vars[10]); pixel->anti_y = lisp_integer(vars[11]); if (lisp_boolean(vars[5])) pixel->flip |= FLIP_HOR; if (lisp_boolean(vars[6])) pixel->flip |= FLIP_VER; pixel->library = library; pixel->next = library->metapixels; library->metapixels = pixel; ++library->num_metapixels; for (channel = 0; channel < NUM_CHANNELS; ++channel) { lst = vars[7 + channel]; if (lisp_list_length(lst) != NUM_SUBPIXELS) { error_info_t info = error_make_string_info(pixel->filename); lisp_stream_free_path(&stream); free_pools(&pools); error_report(ERROR_WRONG_NUM_SUBPIXELS, info); return 0; } else for (i = 0; i < NUM_SUBPIXELS; ++i) { pixel->subpixels_rgb[i * NUM_CHANNELS + channel] = lisp_integer(lisp_car(lst)); lst = lisp_cdr(lst); } } metapixel_complete_subpixel(pixel); /* pixel->data = 0; pixel->collage_positions = 0; */ } else { lisp_stream_free_path(&stream); free_pools(&pools); error_report(ERROR_TABLES_SYNTAX_ERROR, error_make_string_info(library_dir)); return 0; } } else if (type == LISP_TYPE_PARSE_ERROR) { lisp_stream_free_path(&stream); free_pools(&pools); error_report(ERROR_TABLES_PARSE_ERROR, error_make_string_info(library_dir)); return 0; } if (type == LISP_TYPE_EOF) break; } lisp_stream_free_path(&stream); free_pools(&pools); return retval; } library_t* library_new (const char *path) { char *filename = tables_filename(path); int fd; assert(filename != 0); if (access(filename, F_OK) == 0) { error_info_t info = error_make_string_info(filename); free(filename); error_report(ERROR_TABLES_FILE_EXISTS, info); return 0; } fd = open(filename, O_RDWR | O_CREAT, 0666); if (fd == -1) { error_info_t info = error_make_string_info(filename); free(filename); error_report(ERROR_TABLES_FILE_CANNOT_CREATE, info); return 0; } free(filename); return make_library(path); } library_t* library_open_without_reading (const char *path) { char *filename = tables_filename(path); int result; result = access(filename, R_OK | W_OK); if (result == 0) { free(filename); return make_library(path); } else { error_info_t info = error_make_string_info(filename); free(filename); error_report(ERROR_TABLES_FILE_CANNOT_OPEN, info); return 0; } } library_t* library_open (const char *path) { library_t *library = make_library(path); assert(library != 0); if (!read_tables(path, library)) { free_metapixels(library->metapixels); free(library); return 0; } return library; } void library_close (library_t *library) { free_metapixels(library->metapixels); free(library->path); free(library); } metapixel_t* library_add_metapixel (library_t *library, metapixel_t *metapixel) { char bitmap_filename[strlen(library->path) + 1 + strlen(metapixel->name) + 1 + 6 + 1]; char tables_filename[strlen(library->path) + 1 + strlen(TABLES_FILENAME) + 1]; bitmap_t *bitmap; FILE *file; /* get a filename for the bitmap */ sprintf(bitmap_filename, "%s/%s", library->path, metapixel->name); if (access(bitmap_filename, F_OK) == 0) { int i; for (i = 0; i < 1000000; ++i) { sprintf(bitmap_filename, "%s/%s.%06d", library->path, metapixel->name, i); if (access(bitmap_filename, F_OK) == -1) break; } } if (access(bitmap_filename, F_OK) == 0) { error_report(ERROR_CANNOT_FIND_METAPIXEL_IMAGE_NAME, error_make_string_info(bitmap_filename)); return 0; } /* write the bitmap */ if (metapixel->bitmap == 0) bitmap = metapixel_get_bitmap(metapixel); else bitmap = metapixel->bitmap; /* FIXME: check for errors */ bitmap_write(bitmap, bitmap_filename); if (metapixel->bitmap == 0) bitmap_free(bitmap); /* copy the metapixel */ metapixel = copy_metapixel_for_library(metapixel, library, bitmap_filename + strlen(library->path) + 1); assert(metapixel != 0); /* add the metadata to the tables file */ sprintf(tables_filename, "%s/%s", library->path, TABLES_FILENAME); file = fopen(tables_filename, "a"); if (file == 0) { metapixel_free(metapixel); error_report(ERROR_TABLES_FILE_CANNOT_OPEN, error_make_string_info(tables_filename)); return 0; } write_metapixel_metadata(metapixel, file); fclose(file); /* add the metapixel to the library */ metapixel->next = library->metapixels; library->metapixels = metapixel; ++library->num_metapixels; return metapixel; } unsigned int library_count_metapixels (int num_libraries, library_t **libraries) { int i; unsigned int n = 0; for (i = 0; i < num_libraries; ++i) n += libraries[i]->num_metapixels; return n; } library_t* library_find_or_open (int num_libraries, library_t **libraries, const char *library_path, int *num_new_libraries, library_t ***new_libraries) { int i; library_t *library; /* FIXME: we should do better path comparison */ for (i = 0; i < num_libraries; ++i) if (strcmp(libraries[i]->path, library_path) == 0) return libraries[i]; for (i = 0; i < *num_new_libraries; ++i) if (strcmp((*new_libraries)[i]->path, library_path) == 0) return (*new_libraries)[i]; library = library_open(library_path); if (library == 0) return 0; if ((*num_new_libraries)++ == 0) *new_libraries = (library_t**)malloc(sizeof(library_t*)); else *new_libraries = (library_t**)realloc(*new_libraries, *num_new_libraries * sizeof(library_t*)); assert(*new_libraries != 0); (*new_libraries)[*num_new_libraries - 1] = library; return library; }
23.065574
108
0.66409
5a1e41486d18443dd8510f0e4583f1e2295c1116
33,571
c
C
atomgame.c
jwhardwick/Atoms-Game
77afe041572c277566e006ee74bfddc5770c4f27
[ "MIT" ]
1
2017-05-22T05:09:37.000Z
2017-05-22T05:09:37.000Z
atomgame.c
jwhardwick/Atoms-Game
77afe041572c277566e006ee74bfddc5770c4f27
[ "MIT" ]
null
null
null
atomgame.c
jwhardwick/Atoms-Game
77afe041572c277566e006ee74bfddc5770c4f27
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <unistd.h> #include "atomgame.h" int check_convert_int(char* str){ // returns -1 if not a straight integer // returns the int if it's a valid int char *ptr; int result = 0; result = strtol(str, &ptr, 10); //printf("%s result = %d\n", str, result); if(*ptr){ return -1; } return result; } void whose_turn_is_it(index_t* index, int turn) { // I NEED THIS TO HAVE index AND turn FOR EXPANSION int mod_players = 0; mod_players = turn % index->number_of_players; if(mod_players == 0){ mod_players = index->number_of_players; } //printf("mod_players %d\n", mod_players); // need to find out how to return string values // maybe #define some strings? switch(mod_players){ case 1: index->whose_turn_is_it_storage = "Red"; break; case 2: index->whose_turn_is_it_storage = "Green"; break; case 3: index->whose_turn_is_it_storage = "Purple"; break; case 4: index->whose_turn_is_it_storage = "Blue"; break; case 5: index->whose_turn_is_it_storage = "Yellow"; break; case 6: index->whose_turn_is_it_storage = "White"; break; } } void check_for_victory(index_t* index) { // scan over player_stats and see if only one remains int count = 0; for (int i = 0; i < index->number_of_players; i++) { if (index->player_stats[i] != 0) { count += 1; } } //printf("victory count = %d\n", count); if (count == 1) { //victory! // realising a flaw in this system.. to do with adding grids and deciding on their ownership // actually should be fine whose_turn_is_it(index, index->turn_counter); char* turn_ptr = index->whose_turn_is_it_storage; printf("%s Wins\n\n", turn_ptr); handle_quit(index); } } bool is_player_out(index_t* index) { // return True if the player is out int mod_players = 0; mod_players = index->turn_counter % index->number_of_players; if (mod_players == 0){ mod_players = index->number_of_players; } mod_players -= 1; //printf("player_stats[%d] = %d\n", mod_players, index->player_stats[mod_players]); if (index->player_stats[mod_players] == 0) { return true; } return false; } void initialise_grid(index_t* index) { //printf("initialise_grid\n"); for(int i = 0; i < index->height; i++){ for(int j = 0; j < index->width; j++){ index->grid_array[i][j] = NULL; } } } void handle_help(void) { printf("HELP displays this help message\n"); printf("QUIT quits the current game\n\n"); printf("DISPLAY draws the game board in terminal\n"); printf("START <number of players> <width> <height> starts the game\n"); printf("PLACE <x> <y> places an atom in a grid space\n"); printf("UNDO undoes the last move made\n"); printf("STAT displays game statistics\n\n"); printf("SAVE <filename> saves the state of the game\n"); printf("LOAD <filename> loads a save file\n"); printf("PLAYFROM <turn> plays from n steps into the game\n"); } void free_grid_data(index_t* index) { for(int i = 0; i < index->width; i++) { for(int j = 0; j < index->height; j++) { //read grid_array i j // if not null, free if(index->grid_array[i][j] != NULL) { free(index->grid_array[i][j]); } } } } void free_move_data(index_t* index) { //go through move data move_data_t* temp; move_data_t* reader; reader = index->move_data_head; while(reader != NULL) { //wipe data temp = reader->next_turn; free(reader); reader = temp; } } void free_index(index_t* index) { free(index); exit(1); } void handle_quit(index_t* index) { //printf("handle_quit\n"); // need to free the shit out of this program. // go through grid_array and the assosciated data // go through stats_t // free move_data_t completely // free index contents if (index->current_game_state == PRE_GAME || index->current_game_state == GAME_LOADED) { free_index(index); return; } if (index->current_game_state == GAME_STARTED) { free_grid_data(index); free_index(index); return; } free_grid_data(index); free_move_data(index); free_index(index); } void print_move_data(index_t* index) { // prints move data int counter = 1; move_data_t* move_data_reader; move_data_reader = index->move_data_head; for( ; ; ){ printf("turn = %d, x = %d, y = %d, next = %p\n", counter, move_data_reader->x, move_data_reader->y, move_data_reader->next_turn); move_data_reader = move_data_reader->next_turn; counter += 1; if(move_data_reader == NULL){ break; } } } void handle_display(index_t* index) { //printf("handle_display\n"); printf("\n+"); for(int i = 0; i < ((3 * index->width) - 1); i++){ printf("-"); } printf("+\n"); for(int i = 0; i < index->height; i++){ for(int j = 0; j < index->width; j++){ printf("|"); if(index->grid_array[i][j] == NULL){ printf(" "); } else{ printf("%c", index->grid_array[i][j]->player_color); printf("%d", index->grid_array[i][j]->atom_count); } } printf("|\n"); } printf("+"); for(int i = 0; i < ((3 * index->width) - 1); i++){ printf("-"); } printf("+\n\n"); } void start_game(index_t* index, int players, int width, int height) { index->turn_counter = 1; index->turns_played = 1; index->number_of_players = players; index->width = width; index->height = height; // build grid initialise_grid(index); } void handle_start(index_t* index) { //printf("handle_start\n"); if(index->current_game_state != PRE_GAME) { printf("Invalid Command, game already started\n"); return; } int players = 0; int width = 0; int height = 0; char* pptr; char* wptr; char* hptr; char* test; pptr = strtok(NULL, " \n"); //printf("pptr = %s\n", pptr); if(pptr == NULL){ printf("Missing Argument\n"); return; } players = check_convert_int(pptr); wptr = strtok(NULL, " "); //printf("wptr = %s\n", wptr); if(wptr == NULL){ printf("Missing Argument\n"); return; } width = check_convert_int(wptr); hptr = strtok(NULL, " \n"); //printf("hptr = %s\n", hptr); if(hptr == NULL){ printf("Missing Argument\n"); return; } height = check_convert_int(hptr); //printf("players == %d, width == %d, height == %d\n", players, width, height); test = strtok(NULL, " \n"); if(test != NULL){ printf("Too Many Arguments\n"); return; }else if(width < MIN_WIDTH || width > MAX_WIDTH){ printf("Invalid width. Range is 2-255\n"); return; }else if(height < MIN_HEIGHT || height > MAX_HEIGHT){ printf("Invalid height. Range is 2-255\n"); return; }else if(width <= 0 || height <= 0 || players < MIN_PLAYERS || players > MAX_PLAYERS){ printf("Invalid command arguments\n");\ return; }else if( (width * height) < players){ printf("Cannot Start Game\n"); return; } // add variables to struct data // this game state is for fresh game starts index->current_game_state = GAME_STARTED; start_game(index, players, width, height); whose_turn_is_it(index, index->turn_counter); printf("Game Ready\n"); printf("%s's Turn\n\n", index->whose_turn_is_it_storage); } void initialise_new_grid_data(index_t* index, int x, int y) { //printf("initialise_new_grid_data\n"); grid_data_t* new_grid_data; new_grid_data = NULL; new_grid_data = malloc(sizeof(grid_data_t*)); if(new_grid_data == NULL) { printf("malloc failed\n"); } whose_turn_is_it(index, index->turn_counter); new_grid_data->player_color = *index->whose_turn_is_it_storage; new_grid_data->atom_count = 1; index->grid_array[y][x] = new_grid_data; } void add_place_data(index_t* index, int x, int y) { whose_turn_is_it(index, index->turn_counter); char* new_move_player_color = index->whose_turn_is_it_storage; //printf("turn = %d, [ %d, %d ]\n", index->turn_counter, x, y); // move is valid if grid_array[y][x] == NULL; // or player color is equal if(index->grid_array[y][x] == NULL){ //printf("NULL pointer, move is valid!\n"); initialise_new_grid_data(index, x, y); } else if(index->grid_array[y][x]->player_color == new_move_player_color[0]) { //printf("%c owns this square, %c can place here!\n", index->grid_array[y][x]->player_color, new_move_player_color[0]); // send to another function to test if there will be an explosion //printf("sending to check for expansion\n"); check_for_expansion(index, x, y); } else if(index->grid_array[y][x]->player_color != new_move_player_color[0]) { //printf("%c owns this square, %c cannot place here!\n", index->grid_array[y][x]->player_color, new_move_player_color[0]); return; } move_data_t* new_move_data; new_move_data = NULL; new_move_data = malloc(sizeof(move_data_t)); if(new_move_data == NULL) { printf("malloc failed\n"); } new_move_data->x = x; new_move_data->y = y; new_move_data->next_turn = NULL; if(index->current_game_state == GAME_STARTED){ index->move_data_head = new_move_data; } // add to existing move data else if(index->current_game_state == FIRST_ROUND || index->current_game_state == AFTER_FIRST_ROUND){ // loop through index->move_data_head until == NULL // add move_data to end move_data_t* move_data_reader; move_data_reader = index->move_data_head; for( ; ; ){ if(move_data_reader->next_turn == NULL){ move_data_reader->next_turn = new_move_data; break; }else{ move_data_reader = move_data_reader->next_turn; } } // we're now at the end of the most recent move_data addition } //printf("turn_counter = %d\n", index->turn_counter); if (index->turn_counter <= index->number_of_players) { index->current_game_state = FIRST_ROUND; } else if (index->turn_counter > index->number_of_players) { index->current_game_state = AFTER_FIRST_ROUND; } // check for victory if (index->current_game_state == AFTER_FIRST_ROUND) { //printf("checking for victory!\n"); update_stats(index); check_for_victory(index); } // this is the part for new grid data index->turn_counter += 1; index->turns_played += 1; update_stats(index); // check for if someone is out, if they are, turn_counter +=1 if (index->current_game_state == AFTER_FIRST_ROUND) { while (is_player_out(index)) { //printf("player is out!\n"); index->turn_counter += 1; } } } void handle_place(index_t* index) { int x = 0; int y = 0; char* xptr; char* yptr; char* test; xptr = strtok(NULL, " "); //printf("xptr = %s\n", xptr); if(xptr == NULL){ printf("Invalid Coordinates1\n"); return; } x = check_convert_int(xptr); yptr = strtok(NULL, " \n"); //printf("yptr = %s\n", yptr); if(yptr == NULL){ printf("Invalid Coordinates2\n"); return; } y = check_convert_int(yptr); //printf("x == %d, y == %d\n", x, y); test = strtok(NULL, " \n"); if(test != NULL || x < 0 || y < 0 || x >= index->width || y >= index->height){ printf("Invalid Coordinates3\n"); return; } add_place_data(index, x, y); whose_turn_is_it(index, index->turn_counter); char* turn_ptr = index->whose_turn_is_it_storage; printf("%s's Turn\n\n", turn_ptr); } void reset_to_turn(index_t* index) { } void delete_end_move_data(move_data_t* move_data_head) { //printf("delete_end_move_data\n"); move_data_t* move_data_reader = move_data_head; move_data_t* temp = move_data_reader; for ( ; ; ) { if (move_data_reader->next_turn == NULL) { // we are on the last turn free(move_data_reader); temp->next_turn = NULL; break; // memory error here on second turn case. } temp = move_data_reader; move_data_reader = move_data_reader->next_turn; } //printf("delete_end_move_data complete\n"); } move_data_t* copy_move_data(index_t* index) { // reads out all move data up to here DEBUGGG // move_data_t* move_data_x = index->move_data_head; // int countx = 1; // while (move_data_x != NULL) { // printf("turn = %d, [ X, Y ] = [ %d, %d ]\n", countx, move_data_x->x, move_data_x->y); // move_data_x = move_data_x->next_turn; // countx = countx + 1; // } // end DEBUGGG // copy exisitng move data move_data_t* move_data_copy = NULL; move_data_copy = malloc(sizeof(move_data_t)); if(move_data_copy == NULL){ printf("malloc failed\n"); } move_data_t* move_data_copy_head = move_data_copy; move_data_t* move_data_reader = index->move_data_head; //int countz = 1; for ( ; ; ) { move_data_copy->x = move_data_reader->x; move_data_copy->y = move_data_reader->y; move_data_copy->next_turn = move_data_reader->next_turn; // printf("turn = %d, [ X, Y ] = [ %d, %d ]\n", countz, move_data_copy->x, move_data_copy->y); // countz += 1; //free(move_data_reader); --- keeping this seperate move_data_reader = move_data_copy->next_turn; if (move_data_reader == NULL) { break; } // if we're up to here we know we'll need a new move_data_t to hold the next copy move_data_t* new_move_data_copy = NULL; new_move_data_copy = malloc(sizeof(move_data_t)); if(new_move_data_copy == NULL){ printf("malloc failed\n"); } move_data_copy->next_turn = new_move_data_copy; move_data_copy = new_move_data_copy; } // reads out move_data_copy to see it's copied. // move_data_t* move_data_copy_reader = move_data_copy_head; // int count = 1; // printf("\ncopy_reader:\n"); // while (move_data_copy_reader != NULL) { // printf("turn = %d, [ X, Y ] = [ %d, %d ]\n", count, move_data_copy_reader->x, move_data_copy_reader->y); // move_data_copy_reader = move_data_copy_reader->next_turn; // count = count + 1; // } return move_data_copy_head; } void handle_undo(index_t* index) { //printf("handle_undo\n"); if (index->current_game_state == PRE_GAME || index->current_game_state == GAME_LOADED || index->current_game_state == GAME_STARTED) { printf("Error, no move to undo\n"); return; } if (index->turn_counter == 2) { //edge case for setting back to turn 1 //printf("turn 2 edge case = true\n"); // we should just reset the game completely int players = index->number_of_players; int width = index->width; int height = index->height; free_move_data(index); free_grid_data(index); start_game(index, players, width, height); index->current_game_state = GAME_STARTED; start_game(index, players, width, height); whose_turn_is_it(index, index->turn_counter); printf("%s's Turn\n\n", index->whose_turn_is_it_storage); return; } move_data_t* move_data_copy_head = copy_move_data(index); free_move_data(index); // Now i have a copy of move data, time to refresh grid board free_grid_data(index); initialise_grid(index); //now i want to send every x,y turn by turn to //need to remove last move from move_data_copy // for PLAYFROM, i can use the same function delete_end_move_data(move_data_copy_head); index->turn_counter = 1; index->turns_played = 1; index->current_game_state = GAME_STARTED; update_stats(index); //add_place_data(index_t* index, int x, int y); //read through move_data_copy and make turns move_data_t* move_data_copy_move_maker = move_data_copy_head; //int count = 1; //printf("\nmove_maker:\n"); for( ; ; ) { //printf("turn = %d, [ X, Y ] = [ %d, %d ], next = %p\n", count, move_data_copy_move_maker->x, move_data_copy_move_maker->y, move_data_copy_move_maker->next_turn); add_place_data(index, move_data_copy_move_maker->x, move_data_copy_move_maker->y); if (move_data_copy_move_maker->next_turn == NULL) { break; } move_data_copy_move_maker = move_data_copy_move_maker->next_turn; //count = count + 1; } whose_turn_is_it(index, index->turn_counter); char* turn_ptr = index->whose_turn_is_it_storage; printf("%s's Turn\n\n", turn_ptr); return; // i might have to add an edge case to undo move data if only one turn has been played } void update_stats(index_t* index) { // called at the end of every turn // reads through board and updates stats that are stored in index->player_stats //reset stats to 0 for(int i = 0; i < 6; i++){ index->player_stats[i] = 0; //printf("players%d = %d\n", i, players[i]); } // read through index->grid and count scores for(int i = 0; i < index->height; i++) { for(int j = 0; j < index->width; j++){ if(index->grid_array[i][j] != NULL) { char color = index->grid_array[i][j]->player_color; // printf("color = %c\n", color); int count = index->grid_array[i][j]->atom_count; // printf("count = %d\n", count); switch(color){ case 'R': index->player_stats[0] += count; break; case 'G': index->player_stats[1] += count; break; case 'P': index->player_stats[2] += count; break; case 'B': index->player_stats[3] += count; break; case 'Y': index->player_stats[4] += count; break; case 'W': index->player_stats[5] += count; break; default: break; } } } } } void handle_stat(index_t* index) { // up and running // need to add response for if a player has already quit // will implement after handle_quit if (index->current_game_state == PRE_GAME) { printf("Game Not In Progress\n"); return; } update_stats(index); for(int i = 0; i < index->number_of_players; i++) { whose_turn_is_it(index, i+1); char* turn_ptr = index->whose_turn_is_it_storage; printf("Player %s:\n", turn_ptr); if (index->current_game_state == GAME_STARTED || index->current_game_state == FIRST_ROUND || index->current_game_state == GAME_LOADED) { printf("Grid Count: %d\n", index->player_stats[i]); } else if(index->current_game_state == AFTER_FIRST_ROUND) { if (index->player_stats[i] == 0) { printf("Lost\n"); } else { printf("Grid Count: %d\n", index->player_stats[i]); } } if (i < (index->number_of_players - 1)) { printf("\n"); } } printf("\n"); //printf("handle_stat\n"); } void handle_load(index_t* index) { if (index->current_game_state != PRE_GAME) { printf("Restart Application To Load Save\n"); return; } // find name of file to load char* loadptr = NULL; loadptr = strtok(NULL, " \n"); //printf("loadptr = %s\n", loadptr); if(loadptr == NULL){ printf("Missing Argument\n"); return; } char* test = NULL; test = strtok(NULL, " \n"); if(test != NULL){ printf("Too Many Load Arguments\n"); return; } FILE* load_file = NULL; load_file = fopen(loadptr, "r"); if (load_file == NULL) { printf("Cannot Load Save\n"); return; } // find out size of file fseek(load_file, 0L, SEEK_END); int file_size = ftell(load_file); rewind(load_file); printf("file_size = %d\n", file_size); // create array to store the loaded data uint8_t loaded_moves[file_size]; fread(loaded_moves, sizeof(uint8_t), file_size, load_file); fclose(load_file); printf("Game Loaded\n"); index->current_game_state = GAME_LOADED; for(int i = 0; i < file_size; i++) { printf("%d\n", loaded_moves[i]); } // will need to store this loaded data on the heap for next turn. // alternatively I just copy this into move_data now. // i need to initiliase the Game // find out how many turns there are = file_size - 3 / 4 int loaded_turns_played = (file_size - 3) / 4; //printf("loaded turns = %d\n", loaded_turns_played); int requested_turn = 0; while (index->current_game_state == GAME_LOADED) { requested_turn = read_input_after_load(index, loaded_turns_played); } printf("requested_turn = %d\n", requested_turn); // sick! we're live. Now we can just load up to this turn // now initialise the game int width = loaded_moves[0]; int height = loaded_moves[1]; int players = loaded_moves[2]; // test loaded parameters to ensure validity if(width < MIN_WIDTH || width > MAX_WIDTH){ printf("Invalid width. Save file is corrupt\n"); return; }else if(height < MIN_HEIGHT || height > MAX_HEIGHT){ printf("Invalid height. Save file is corrupt\n"); return; }else if(width <= 0 || height <= 0 || players < MIN_PLAYERS || players > MAX_PLAYERS){ printf("Invalid start parameters. Save file is corrupt\n");\ return; }else if( (width * height) < players){ printf("Cannot Load Game. Save file is corrupt\n"); return; } start_game(index, players, width, height); // now play the game! index->current_game_state = GAME_STARTED; for (int i = 0 ; i < requested_turn; i++) { //printf("i = %d, [ X, Y ] = [ %d, %d ]\n", i, loaded_moves[3 + (i * 4)], loaded_moves[4 + (i * 4)]); add_place_data(index, loaded_moves[3 + (i * 4)], loaded_moves[4 + (i * 4)]); } printf("Game Ready\n"); whose_turn_is_it(index, index->turn_counter); char* turn_ptr = index->whose_turn_is_it_storage; printf("%s's Turn\n\n", turn_ptr); return; } void handle_save(index_t* index) { // ******** need to read in SAVE file name char* saveptr = NULL; saveptr = strtok(NULL, " \n"); //printf("loadptr = %s\n", loadptr); if(saveptr == NULL){ printf("Missing Save Argument\n"); return; } char* test = NULL; test = strtok(NULL, " \n"); if(test != NULL){ printf("Too Many Save Arguments\n"); return; } //read through move_data, store values as uint8_t uint8_t saved_moves[(index->turns_played - 1) * 4]; uint8_t header[3]; header[0] = index->width; header[1] = index->height; header[2] = index->number_of_players; // read move data to an array of uint8_t move_data_t* reader = index->move_data_head; //printf("turns_played%d\n", index->turns_played); for (int i = 0; i < (index->turns_played - 1); i++) { saved_moves[(4 * i) + 0] = reader->x; saved_moves[(4 * i) + 1] = reader->y; saved_moves[(4 * i) + 2] = 0; saved_moves[(4 * i) + 3] = 0; if (reader->next_turn == NULL) { break; } reader = reader->next_turn; } if (0 == access(saveptr, 0)) { printf("File Already Exists\n"); return; } FILE* save_file = NULL; save_file = fopen(saveptr, "w"); if (save_file == NULL) { perror("Unable to open file for writing"); return; } fwrite(header, sizeof(uint8_t), 3, save_file); fwrite(saved_moves, sizeof(uint8_t), ((index->turns_played - 1) * 4), save_file); fclose(save_file); handle_load(index); } int handle_playfrom(index_t* index, int loaded_turns_played) { char* playptr = NULL; playptr = strtok(NULL, " \n"); //printf("playptr = %s\n", playptr); if(playptr == NULL){ printf("Missing Argument\n"); return 0; } char* test = NULL; test = strtok(NULL, "\n"); if(test != NULL){ printf("Too Many Load Arguments\n"); return 0; } if(strcmp(playptr, "END\n") == 0){ return loaded_turns_played; } int requested_turn = 0; requested_turn = check_convert_int(playptr); // and <= number of moves made if (requested_turn <= 0) { printf("Invalid Turn Number\n"); return 0; } if (requested_turn > loaded_turns_played) { return loaded_turns_played; } return requested_turn; } void check_for_expansion(index_t* index, int x, int y) { // function also adds to atom_count. // check if the grid square is already at the max // if no, then atom_count += 1 and gtfo // if yes, trigger explosion // corner = 2, side = 3, else = 4; // so max = above -1; if( (x < 0) || (x >= index->width) || (y < 0) || (y >= index->height)) { // pretty sure this test is redundant as I now do corners/sides case by case // thus no chance of going off the game board return; } //printf("checking for expansion\n"); // this test checks if the grid square has no move in it if(index->grid_array[y][x] == NULL) { //printf("null pointer found\n"); // if no grid, create data for that grid square initialise_new_grid_data(index, x, y); return; } //reject negatives or board limits // corner testing if( (x == 0 && y == 0) || (x == 0 & y == (index->height - 1)) || (x == (index->width - 1) && y == 0) || (x == (index->width -1) && y == (index->height -1)) ) { //printf("corner x = %d y = %d\n", x, y); if(index->grid_array[y][x]->atom_count == 1) { clear_move_data_after_explosion(index, x, y); trigger_explosion_corner(index, x, y); update_stats(index); check_for_victory(index); return; } } // side testing else if( (x == 0) || (x == index->width - 1) || (y == 0) || (y == index->height - 1) ) { //printf("side x = %d y = %d\n", x, y); if(index->grid_array[y][x]->atom_count == 2) { clear_move_data_after_explosion(index, x, y); trigger_explosion_side(index, x, y); update_stats(index); check_for_victory(index); return; } } // else - must be neither side nor corner else{ if(index->grid_array[y][x]->atom_count == 3) { clear_move_data_after_explosion(index, x, y); trigger_explosion_middle(index, x, y); update_stats(index); check_for_victory(index); return; } } // if no explosion is triggered, grid_data is updated // makes sure the player_color is whoevers turn it is (for explosions) index->grid_array[y][x]->atom_count += 1; whose_turn_is_it(index, index->turn_counter); index->grid_array[y][x]->player_color = *index->whose_turn_is_it_storage; return; } void clear_move_data_after_explosion(index_t* index, int x, int y) { // need to clear up exisiting grid data, free it etc. // i malloc'd grid_data_t free(index->grid_array[y][x]); index->grid_array[y][x] = NULL; } void trigger_explosion_corner(index_t* index, int x, int y) { // we already know its a corner, so explosion will be 2. // easiest to just do individual testing for each cases // i.e ( x0, y0 ), ( x(w-1), y0 ), ( x0, y(h-1) ), ( x(w-1), y(h-1) ) if (x == 0 && y == 0) { // top left - right,down check_for_expansion(index, (x + 1), y); // right check_for_expansion(index, x, (y + 1)); // down } else if (x == 0 && y == (index->height - 1)) { // bottom left - up, right check_for_expansion(index, x, (y - 1)); // up check_for_expansion(index, (x + 1), y); // right } else if (x == (index->width - 1) && y == 0) { // top right - down, left check_for_expansion(index, x, (y + 1)); // down check_for_expansion(index, (x - 1), y); // left } else if (x == (index->width - 1) && y == (index->height - 1)) { // bottom right - left, up check_for_expansion(index, (x - 1), y); // left check_for_expansion(index, x, (y - 1)); // up } } void trigger_explosion_side(index_t* index, int x, int y) { // left x == 0, right x == w-1, up y == 0, down y == h-1 // need to clear up exisiting grid data, free it etc. if (x == 0) { //left - up, right, down check_for_expansion(index, x, (y - 1)); // up check_for_expansion(index, (x + 1), y); // right check_for_expansion(index, x, (y + 1)); // down } else if (x == (index->width - 1)) { //right - up, down, left check_for_expansion(index, x, (y - 1)); // up check_for_expansion(index, x, (y + 1)); // down check_for_expansion(index, (x - 1), y); // left } else if (y == 0) { //top - right, down, left check_for_expansion(index, (x + 1), y); // right check_for_expansion(index, x, (y + 1)); // down check_for_expansion(index, (x - 1), y); // left } else if (y == (index->height - 1)) { //bottom - up, right, left check_for_expansion(index, x, (y - 1)); // up check_for_expansion(index, (x + 1), y); // right check_for_expansion(index, (x - 1), y); // left } } void trigger_explosion_middle(index_t* index, int x, int y) { // always up, right, down, left check_for_expansion(index, x, (y - 1)); // up check_for_expansion(index, (x + 1), y); // right check_for_expansion(index, x, (y + 1)); // down check_for_expansion(index, (x - 1), y); // left } void add_move_to_grid(index_t* index, int x, int y) { // update move_data // update grid } void read_input(index_t* index) { char buffer[5000]; fgets(buffer, sizeof(buffer), stdin); char* command; command = strtok(buffer, " "); if(strcmp(command, "HELP\n") == 0){ //printf("help\n"); handle_help(); } else if(strcmp(command, "QUIT\n") == 0){ //printf("quit\n"); printf("Bye!\n"); handle_quit(index); } else if(strcmp(command, "DISPLAY\n") == 0){ //printf("display\n"); handle_display(index); } else if(strcmp(command, "START") == 0){ //printf("start\n"); handle_start(index); } else if(strcmp(command, "PLACE") == 0){ //printf("place\n"); handle_place(index); } else if(strcmp(command, "UNDO\n") == 0){ //printf("undo\n"); handle_undo(index); } else if(strcmp(command, "STAT\n") == 0){ //printf("stat\n"); handle_stat(index); } else if(strcmp(command, "SAVE") == 0){ //printf("save\n"); handle_save(index); } else if(strcmp(command, "LOAD") == 0){ //printf("load\n"); handle_load(index); } else if(strcmp(command, "PLAYFROM") == 0){ printf("Invalid Command\n"); } else{ printf("Invalid input, type HELP for instructions\n"); } } int read_input_after_load(index_t* index, int loaded_turns_played) { char buffer[5000]; fgets(buffer, sizeof(buffer), stdin); char* command; command = strtok(buffer, " "); if(strcmp(command, "QUIT\n") == 0){ //printf("quit\n"); printf("Bye!\n"); handle_quit(index); return 0; }else if(strcmp(command, "PLAYFROM") == 0){ //printf("playfrom\n"); // handle_playfrom returns the requested to playfrom int playfrom_result = 0; playfrom_result = handle_playfrom(index, loaded_turns_played); if (playfrom_result > 0) { index->current_game_state = VALID_PLAYFROM; return playfrom_result; } }else{ printf("Invalid Command\n"); return 0; } return 0; } int main() { index_t* index_main; index_main = NULL; index_main = malloc(sizeof(index_t)); if(index_main == NULL){ printf("malloc failed\n"); } // copy of index_main index_t* index; index = NULL; index = index_main; index->current_game_state = PRE_GAME; for( ; ; ) { read_input(index); } return 0; }
31.46298
171
0.574424
05259b974cfb213bd27a3be5dcb8c365f3525743
12,534
h
C
arcane/src/arcane/IVariableMng.h
JeromeDuboisPro/framework
d88925495e3787fdaf640c29728dcac385160188
[ "Apache-2.0" ]
null
null
null
arcane/src/arcane/IVariableMng.h
JeromeDuboisPro/framework
d88925495e3787fdaf640c29728dcac385160188
[ "Apache-2.0" ]
null
null
null
arcane/src/arcane/IVariableMng.h
JeromeDuboisPro/framework
d88925495e3787fdaf640c29728dcac385160188
[ "Apache-2.0" ]
null
null
null
// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*- //----------------------------------------------------------------------------- // Copyright 2000-2021 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com) // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: Apache-2.0 //----------------------------------------------------------------------------- /*---------------------------------------------------------------------------*/ /* IVariableMng.h (C) 2000-2020 */ /* */ /* Interface du gestionnaire des variables. */ /*---------------------------------------------------------------------------*/ #ifndef ARCANE_IVARIABLEMNG_H #define ARCANE_IVARIABLEMNG_H /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ #include "arcane/ArcaneTypes.h" /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ namespace Arcane { /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ class IVariable; class IVariableFilter; class VariableInfo; class MeshVariable; class IModule; class IMsg; class IDataReader; class IDataWriter; class IObservable; class ICheckpointReader; class CheckpointReadInfo; class ICheckpointWriter; class IPostProcessorWriter; class VariableRef; class IMesh; class IVariableUtilities; class VariableStatusChangedEventArgs; /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*! * \brief Interface du gestionnaire de variables. * * Ce gestionnaire contient la liste des variables déclarées dans le * sous-domaine associé \a subDomain(). Il maintient la liste des variables * et permet de les lire ou de les écrire. */ class IVariableMng { public: virtual ~IVariableMng() {} //!< Libère les ressources. public: /*! * \brief Construit les membres de l'instance. * * L'instance n'est pas utilisable tant que cette méthode n'a pas été * appelée. Cette méthode doit être appelée avant initialize(). * \warning Cette méthode ne doit être appelée qu'une seule fois. */ virtual void build() =0; /*! * \brief Initialise l'instance. * L'instance n'est pas utilisable tant que cette méthode n'a pas été * appelée. * \warning Cette méthode ne doit être appelée qu'une seule fois. */ virtual void initialize() =0; //! Supprime et détruit les variables gérées par ce gestionnaire virtual void removeAllVariables() =0; //! Détache les variables associées au maillage \a mesh. virtual void detachMeshVariables(IMesh* mesh) =0; public: //! Gestionnaire du sous-domaine ARCCORE_DEPRECATED_2020("Do not use this method. Try to get 'ISubDomain' from another way") virtual ISubDomain* subDomain() =0; //! Gestionnaire de messages virtual ITraceMng* traceMng() =0; /*! * \brief Ajoute une référence à une variable. * * Ajoute la référence \a var au gestionnaire. * * \pre var != 0 * \pre var ne doit pas déjà être référencée. * \return l'implémentation associée à \a var. */ virtual void addVariableRef(VariableRef* var) =0; /*! * \brief Supprime une référence à une variable. * * Supprime la référence \a var du gestionnaire. * * Si \a var n'est pas référencée par le gestionnaire, rien n'est effectué. * \pre var != 0 */ virtual void removeVariableRef(VariableRef* var) =0; /*! * \brief Ajoute une variable. * * Ajoute la variable \a var. * * La validité de la variable n'est pas effectuée (void checkVariable()). * * \pre var != 0 * \pre var ne doit pas déjà être référencée. * \return l'implémentation associée à \a var. */ virtual void addVariable(IVariable* var) =0; /*! * \brief Supprime une variable. * * Supprime la variable \a var. * * Après appel à cette méthode, la variable ne doit plus être utilisée. * * \pre var != 0 * \pre var doit avoir une seule référence. */ virtual void removeVariable(IVariable* var) =0; /*! * \brief Vérifie une variable. * * Vérifie que la variable de nom \a name caractérisée par \a infos est valide * C'est le cas si et seulement si: * - aucune variable de nom \a infos.name() n'existe déjà. * - une variable de nom \a infos.name() existe et * son type et son genre correspondent \a infos. * * Si la variable n'est pas valide, une exception est lancée. * * Cette opération est utilisée lorsqu'on souhaite créer une * nouvelle référence à une variable et permet de s'assurer qu'elle * sera valide. * * \exception ExBadVariableKindType si la variable de nom \a infos.name() existe * et que son type et le genre ne correspondent pas à ceux de \a infos. * * \return la variable de \a infos.name() si elle existe, 0 sinon */ virtual IVariable* checkVariable(const VariableInfo& infos) =0; /*! * \brief Initialise les variables. * * Parcours la liste des variables et les initialisent. * Seules les variables d'un module utilisé sont initialisées. * * \param is_continue \a true vrai si on est en reprise. */ virtual void initializeVariables(bool is_continue) =0; /*! \brief Génère un nom pour une variable temporaire. * * Pour assurer la cohérence de ce nom, il faut que tous les sous-domaines * appellent cette fonction. */ virtual String generateTemporaryVariableName() =0; //! Affiche la liste des variables du gestionnaire lié à un module virtual void dumpList(std::ostream&,IModule*) =0; //! Affiche la liste de toutes les variables du gestionnaire virtual void dumpList(std::ostream&) =0; /*! * \brief Taille estimé pour exporter des variables. * Cette opération estime le nombre de méga octets que va générer l'exportation des variables \a vars. Si \a vars est vide, l'estimation porte sur toutes les variables référencées. L'estimation tient compte uniquement de la quantité mémoire utilisée par les variables et pas de l'écrivain utilisé. L'estimation est locale au sous-domaine. Pour obtenir la taille totale d'une exportation, il faut effectuer déterminer la taille par sous-domaine et faire la somme. Cette méthode est collective \todo utiliser des entiers 8 octets voir plus... */ virtual Real exportSize(const VariableCollection& vars) =0; /*! * \brief Observable pour les variables en écriture. * * Les observateurs enregistrés dans cet observable sont appelés * avant d'écrire les variables (opération writeCheckpoint(), * writeVariables() ou writePostProcessing()). */ virtual IObservable* writeObservable() =0; /*! * \brief Observable pour les variables en lecture. * * Les observateurs enregistrés dans cet observable sont appelés * après avoir lu les variables (opération readVariables() ou readCheckpoint()). */ virtual IObservable* readObservable() =0; /*! \brief Ecrit les variables. * * Parcours l'ensemble des variables du gestionnaire et leur applique l'écrivain * \a writer. Si \a filter est non nul, il est appliqué à chaque variable et * une variable n'est écrite que si le filtre est vrai pour cette variable. * * Cette méthode est collective */ virtual void writeVariables(IDataWriter* writer,IVariableFilter* filter=0) =0; /*! * \brief Exporte les variables. * * Exporte les variables de la liste \a vars. Si \a vars est * vide, exporte toutes les variables de la base qui sont utilisées. */ virtual void writeVariables(IDataWriter* writer,const VariableCollection& vars) =0; /*! * \internal * \brief Ecrit les variables pour une protection. * * Utilise le service de protection \a writer pour écrire les variables. * * Cette méthode est collective. * * Cette méthode est interne à Arcane. En générel, l'écriture * d'une protection se fait via une instance de ICheckpointMng, * accessible via ISubDomain::checkpointMng(). */ virtual void writeCheckpoint(ICheckpointWriter* writer) =0; /*! \brief Ecrit les variables pour un post-traitement. * * Utilise le service de post-traitement \a writer pour écrire les variables. * L'appelant doit avoir positionner les champs de \a writer avant cet appel, * notamment la liste des variables à post-traiter. Cette méthode * appelle IPostProcessorWriter::notifyBeginWrite() avant l'écriture * et IPostProcessorWriter::notifyEndWriter() en fin. * * Cette méthode est collective. */ virtual void writePostProcessing(IPostProcessorWriter* writer) =0; /*! *\brief Relit toutes les variables. * * Parcours l'ensemble des variables du gestionnaire et leur applique le lecteur * \a reader. Si \a filter est non nul, il est appliqué à chaque variable et * une variable n'est lue que si le filtre est vrai pour cette variable. Les * variables qui ne sont pas lues ne sont pas modifiées par cette opération. * * \deprecated Utiliser readVariable(IDataReader*) * * Cette méthode est collective. */ virtual void readVariables(IDataReader* reader,IVariableFilter* filter=0) =0; /*! * \internal * \brief Relit toutes les variables d'une protection. * * Lit une protection avec le service \a reader sur l'ensemble * des variables. * * Cette méthode est collective. * * Cette méthode est interne à Arcane. En générel, la lecture * d'une protection se fait via une instance de ICheckpointMng, * accessible via ISubDomain::checkpointMng(). */ virtual void readCheckpoint(ICheckpointReader* reader) =0; /*! * \internal * \brief Relit toutes les variables d'une protection. * * Lit une protection avec les informations contenues * dans \a infos. * * Cette méthode est collective. * * Cette méthode est interne à Arcane. En générel, la lecture * d'une protection se fait via une instance de ICheckpointMng, * accessible via ISubDomain::checkpointMng(). */ virtual void readCheckpoint(const CheckpointReadInfo& infos) =0; //! Donne l'ensemble des variables du module \a i virtual void variables(VariableRefCollection v,IModule* i) =0; //! Liste des variables virtual VariableCollection variables() =0; //! Liste des variables utilisées virtual VariableCollection usedVariables() =0; //! Notifie au gestionnaire que l'état d'une variable a changé virtual void notifyUsedVariableChanged() =0; //! Retourne la variable de nom \a name ou 0 si aucune de se nom existe. virtual IVariable* findVariable(const String& name) =0; //! Retourne la variable du maillage de nom \a name ou 0 si aucune de se nom existe. virtual IVariable* findMeshVariable(IMesh* mesh,const String& name) =0; //! Retourne la variable de nom complet \a name ou 0 si aucune de se nom existe. virtual IVariable* findVariableFullyQualified(const String& name) =0; //! Ecrit les statistiques sur les variables sur le flot \a ostr virtual void dumpStats(std::ostream& ostr,bool is_verbose) =0; //! Ecrit les statistiques avec l'écrivain \a writer. virtual void dumpStatsJSON(JSONWriter& writer) =0; //! Interface des fonctions utilitaires associées virtual IVariableUtilities* utilities() const =0; public: //! \name Evènements //@{ //! Evènement envoyé lorsqu'une variable est créée virtual EventObservable<const VariableStatusChangedEventArgs&>& onVariableAdded() =0; //! Evènement envoyé lorsqu'une variable est détruite virtual EventObservable<const VariableStatusChangedEventArgs&>& onVariableRemoved() =0; //@} public: /*! * \internal * Fonction interne temporaire pour récupérer le sous-domaine. */ virtual ISubDomain* _internalSubDomain() const =0; }; /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ } // End namespace Arcane /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ #endif
33.784367
93
0.628052
e56b5c1cbb5443a1092cf34cfaa1cb7e48495e6b
197
c
C
lib/my/my_putstr.c
ThomasMarches/my_rpg
d81719cc6240408ad570638fa544958d4c002627
[ "MIT" ]
null
null
null
lib/my/my_putstr.c
ThomasMarches/my_rpg
d81719cc6240408ad570638fa544958d4c002627
[ "MIT" ]
null
null
null
lib/my/my_putstr.c
ThomasMarches/my_rpg
d81719cc6240408ad570638fa544958d4c002627
[ "MIT" ]
null
null
null
/* ** EPITECH PROJECT, 2019 ** MUL_my_rpg_2019 ** File description: ** my_putstr.c */ #include "my.h" #include <unistd.h> void my_putstr(char *string) { write(1, string, my_strlen(string)); }
14.071429
40
0.670051
e58ad5adb1da49da3db6c5481f4e5712a34c0b3c
2,132
h
C
include/AST/ASTNodeBase.h
fly-lang/fly
4c219c5c5cdb16a8d341de28a1e15f1109c7cfdf
[ "Apache-2.0" ]
3
2021-01-29T09:00:19.000Z
2021-08-29T18:36:35.000Z
include/AST/ASTNodeBase.h
fly-lang/fly
4c219c5c5cdb16a8d341de28a1e15f1109c7cfdf
[ "Apache-2.0" ]
30
2021-02-07T23:19:05.000Z
2022-03-23T10:28:55.000Z
include/AST/ASTNodeBase.h
fly-lang/fly
4c219c5c5cdb16a8d341de28a1e15f1109c7cfdf
[ "Apache-2.0" ]
2
2022-02-18T02:51:54.000Z
2022-03-29T20:48:32.000Z
//===--------------------------------------------------------------------------------------------------------------===// // include/AST/ASTNodeBase.h - Base AST Node // // Part of the Fly Project https://flylang.org // Under the Apache License v2.0 see LICENSE for details. // Thank you to LLVM Project https://llvm.org/ // //===--------------------------------------------------------------------------------------------------------------===// #ifndef FLY_ASTNODEBASE_H #define FLY_ASTNODEBASE_H #include "ASTFunc.h" #include "Basic/SourceLocation.h" #include "llvm/ADT/StringMap.h" namespace fly { class ASTContext; class ASTGlobalVar; class ASTClass; class ASTFunc; class ASTFuncCall; class ASTUnrefGlobalVar; class ASTUnrefCall; class ASTNodeBase { protected: ASTContext* Context; // Node FileName const llvm::StringRef Name; // Private Global Vars llvm::StringMap<ASTGlobalVar *> GlobalVars; // Public Functions std::unordered_set<ASTFunc*> Functions; // Calls created on Functions creations, each Function have a Call defined here llvm::StringMap<std::vector<ASTFuncCall *>> FunctionCalls; // Public Classes llvm::StringMap<ASTClass *> Classes; // Contains all unresolved VarRef to a GlobalVar std::vector<ASTUnrefGlobalVar *> UnrefGlobalVars; // Contains all unresolved Function Calls std::vector<ASTUnrefCall *> UnrefFunctionCalls; public: ASTNodeBase() = delete; ASTNodeBase(const llvm::StringRef &Name, ASTContext* Context); const llvm::StringRef& getName(); ASTContext &getContext() const; const llvm::StringMap<ASTGlobalVar *> &getGlobalVars() const; const std::unordered_set<ASTFunc*> &getFunctions() const; const llvm::StringMap<std::vector<ASTFuncCall *>> &getFunctionCalls() const; const llvm::StringMap<ASTClass *> &getClasses() const; bool AddFunctionCall(ASTFuncCall *Call); virtual std::string str() const; }; } #endif //FLY_ASTNODEBASE_H
26.320988
120
0.588649
8cb6055929349773ba8a86e0f5af029e00d48643
543
h
C
MicroBlink.framework/Headers/MBVinParser.h
MicroblinkTechSupport/blinkid-ios
0d58db758c2572b21569d2a7d6b45dd6b45d11a2
[ "Apache-2.0" ]
1
2018-12-19T04:08:14.000Z
2018-12-19T04:08:14.000Z
MicroBlink.framework/Headers/MBVinParser.h
MicroblinkTechSupport/blinkid-ios
0d58db758c2572b21569d2a7d6b45dd6b45d11a2
[ "Apache-2.0" ]
null
null
null
MicroBlink.framework/Headers/MBVinParser.h
MicroblinkTechSupport/blinkid-ios
0d58db758c2572b21569d2a7d6b45dd6b45d11a2
[ "Apache-2.0" ]
null
null
null
// // MBVinParser.h // MicroBlinkDev // // Created by Jura Skrlec on 07/03/2018. // #import <Foundation/Foundation.h> #import "MBMicroBlinkDefines.h" #import "MBParser.h" #import "MBVinParserResult.h" #import "MBMicroBlinkInitialization.h" NS_ASSUME_NONNULL_BEGIN /** * MBVinParser is used for parsing VIN numbers */ MB_CLASS_AVAILABLE_IOS(8.0) MB_FINAL @interface MBVinParser : MBParser <NSCopying> MB_INIT /** * Vin parser result */ @property (nonatomic, strong, readonly) MBVinParserResult *result; @end NS_ASSUME_NONNULL_END
16.96875
66
0.751381
ef7f3343f4eb6da18e7dd5d566858c9571b42fe3
468
h
C
Frameworks/HealthKit.framework/_HKCFGDoubleTerminal.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
36
2016-04-20T04:19:04.000Z
2018-10-08T04:12:25.000Z
Frameworks/HealthKit.framework/_HKCFGDoubleTerminal.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
null
null
null
Frameworks/HealthKit.framework/_HKCFGDoubleTerminal.h
shaojiankui/iOS10-Runtime-Headers
6b0d842bed0c52c2a7c1464087b3081af7e10c43
[ "MIT" ]
10
2016-06-16T02:40:44.000Z
2019-01-15T03:31:45.000Z
/* Generated by RuntimeBrowser Image: /System/Library/Frameworks/HealthKit.framework/HealthKit */ @interface _HKCFGDoubleTerminal : _HKCFGTerminal { id /* block */ _condition; } @property (nonatomic, copy) id /* block */ condition; - (void).cxx_destruct; - (id)_label; - (unsigned long long)_minimumLength; - (bool)_scanValue:(id*)arg1 withScanner:(id)arg2; - (id)characterSet; - (id /* block */)condition; - (void)setCondition:(id /* block */)arg1; @end
23.4
66
0.700855
b4a2864dbf3e2d8563f51c46d907f652ccc7a2e2
5,920
c
C
extern/gtk/tests/listmodel.c
PableteProgramming/download
013e35bb5c085e5dfdb57a3a0a39cdf2fd3064b8
[ "MIT" ]
null
null
null
extern/gtk/tests/listmodel.c
PableteProgramming/download
013e35bb5c085e5dfdb57a3a0a39cdf2fd3064b8
[ "MIT" ]
null
null
null
extern/gtk/tests/listmodel.c
PableteProgramming/download
013e35bb5c085e5dfdb57a3a0a39cdf2fd3064b8
[ "MIT" ]
null
null
null
#include <gtk/gtk.h> enum { PROP_LABEL = 1, PROP_ID, LAST_PROPERTY }; static GParamSpec *properties[LAST_PROPERTY] = { NULL, }; typedef struct { GObject parent; char *label; int id; } MyObject; typedef struct { GObjectClass parent_class; } MyObjectClass; static GType my_object_get_type (void); G_DEFINE_TYPE (MyObject, my_object, G_TYPE_OBJECT) static void my_object_init (MyObject *obj) { } static void my_object_get_property (GObject *object, guint property_id, GValue *value, GParamSpec *pspec) { MyObject *obj = (MyObject *)object; switch (property_id) { case PROP_LABEL: g_value_set_string (value, obj->label); break; case PROP_ID: g_value_set_int (value, obj->id); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); break; } } static void my_object_set_property (GObject *object, guint property_id, const GValue *value, GParamSpec *pspec) { MyObject *obj = (MyObject *)object; switch (property_id) { case PROP_LABEL: g_free (obj->label); obj->label = g_value_dup_string (value); break; case PROP_ID: obj->id = g_value_get_int (value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); break; } } static void my_object_finalize (GObject *obj) { MyObject *object = (MyObject *)obj; g_free (object->label); G_OBJECT_CLASS (my_object_parent_class)->finalize (obj); } static void my_object_class_init (MyObjectClass *class) { GObjectClass *object_class = G_OBJECT_CLASS (class); object_class->get_property = my_object_get_property; object_class->set_property = my_object_set_property; object_class->finalize = my_object_finalize; properties[PROP_LABEL] = g_param_spec_string ("label", "label", "label", NULL, G_PARAM_READWRITE); properties[PROP_ID] = g_param_spec_int ("id", "id", "id", 0, G_MAXINT, 0, G_PARAM_READWRITE); g_object_class_install_properties (object_class, LAST_PROPERTY, properties); } static GtkWidget * create_widget (gpointer item, gpointer user_data) { MyObject *obj = (MyObject *)item; GtkWidget *label; label = gtk_label_new (""); g_object_bind_property (obj, "label", label, "label", G_BINDING_SYNC_CREATE); return label; } static int compare_items (gconstpointer a, gconstpointer b, gpointer data) { int id_a, id_b; g_object_get ((gpointer)a, "id", &id_a, NULL); g_object_get ((gpointer)b, "id", &id_b, NULL); return id_a - id_b; } static void add_some (GtkButton *button, GListStore *store) { int n, i; guint n_items; GObject *obj; char *label; for (n = 0; n < 50; n++) { n_items = g_list_model_get_n_items (G_LIST_MODEL (store)); i = g_random_int_range (0, MAX (2 * n_items, 1)); label = g_strdup_printf ("Added %d", i); obj = g_object_new (my_object_get_type (), "id", i, "label", label, NULL); g_list_store_insert_sorted (store, obj, compare_items, NULL); g_object_unref (obj); g_free (label); } } static void remove_some (GtkButton *button, GListStore *store) { int n, i; guint n_items; for (n = 0; n < 50; n++) { n_items = g_list_model_get_n_items (G_LIST_MODEL (store)); if (n_items == 0) return; i = g_random_int_range (0, n_items); g_list_store_remove (store, i); } } int main (int argc, char *argv[]) { GtkWidget *window, *grid, *sw, *box, *button; GListStore *store; int i; gtk_init (); store = g_list_store_new (my_object_get_type ()); for (i = 0; i < 100; i++) { MyObject *obj; char *label; label = g_strdup_printf ("item %d", i); obj = g_object_new (my_object_get_type (), "id", i, "label", label, NULL); g_list_store_append (store, obj); g_free (label); g_object_unref (obj); } window = gtk_window_new (); grid = gtk_grid_new (); gtk_window_set_child (GTK_WINDOW (window), grid); sw = gtk_scrolled_window_new (); gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (sw), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); gtk_widget_set_hexpand (sw, TRUE); gtk_widget_set_vexpand (sw, TRUE); gtk_grid_attach (GTK_GRID (grid), sw, 0, 0, 1, 1); box = gtk_list_box_new (); gtk_list_box_bind_model (GTK_LIST_BOX (box), G_LIST_MODEL (store), create_widget, NULL, NULL); gtk_scrolled_window_set_child (GTK_SCROLLED_WINDOW (sw), box); sw = gtk_scrolled_window_new (); gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (sw), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); gtk_widget_set_hexpand (sw, TRUE); gtk_widget_set_vexpand (sw, TRUE); gtk_grid_attach (GTK_GRID (grid), sw, 1, 0, 1, 1); box = gtk_flow_box_new (); gtk_flow_box_bind_model (GTK_FLOW_BOX (box), G_LIST_MODEL (store), create_widget, NULL, NULL); gtk_scrolled_window_set_child (GTK_SCROLLED_WINDOW (sw), box); button = gtk_button_new_with_label ("Add some"); g_signal_connect (button, "clicked", G_CALLBACK (add_some), store); gtk_grid_attach (GTK_GRID (grid), button, 0, 1, 1, 1); button = gtk_button_new_with_label ("Remove some"); g_signal_connect (button, "clicked", G_CALLBACK (remove_some), store); gtk_grid_attach (GTK_GRID (grid), button, 0, 2, 1, 1); gtk_widget_show (window); while (TRUE) g_main_context_iteration (NULL, TRUE); return 0; }
25.191489
96
0.624324
a6eaae58fe156df15a92a02ac1b598bfa5c9bd43
21,384
h
C
src/xrt/auxiliary/vk/vk_helpers.h
SimulaVR/monado
b5d46eebf5f9b7f96a52639484a1b35d8ab3cd21
[ "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "BSL-1.0", "BSD-3-Clause" ]
2
2021-11-08T05:17:12.000Z
2022-01-24T12:50:59.000Z
src/xrt/auxiliary/vk/vk_helpers.h
SimulaVR/monado
b5d46eebf5f9b7f96a52639484a1b35d8ab3cd21
[ "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
src/xrt/auxiliary/vk/vk_helpers.h
SimulaVR/monado
b5d46eebf5f9b7f96a52639484a1b35d8ab3cd21
[ "Unlicense", "Apache-2.0", "BSD-2-Clause", "MIT", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
// Copyright 2019-2020, Collabora, Ltd. // SPDX-License-Identifier: BSL-1.0 /*! * @file * @brief Common Vulkan code header. * @author Jakob Bornecrantz <jakob@collabora.com> * @author Lubosz Sarnecki <lubosz.sarnecki@collabora.com> * @ingroup aux_vk */ #pragma once #include "xrt/xrt_compositor.h" #include "xrt/xrt_vulkan_includes.h" #include "xrt/xrt_handles.h" #include "util/u_logging.h" #include "os/os_threading.h" #ifdef __cplusplus extern "C" { #endif /* * * Structs * */ /*! * A bundle of Vulkan functions and objects, used by both @ref comp and @ref * comp_client. Note that they both have different instances of the object and * as such VkInstance and so on. * * @ingroup aux_vk */ struct vk_bundle { enum u_logging_level ll; VkInstance instance; VkPhysicalDevice physical_device; int physical_device_index; VkDevice device; uint32_t queue_family_index; uint32_t queue_index; VkQueue queue; struct os_mutex queue_mutex; bool has_GOOGLE_display_timing; bool has_EXT_global_priority; bool has_VK_EXT_robustness2; bool is_tegra; VkDebugReportCallbackEXT debug_report_cb; VkPhysicalDeviceMemoryProperties device_memory_props; VkCommandPool cmd_pool; struct os_mutex cmd_pool_mutex; // clang-format off // Loader functions PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr; PFN_vkCreateInstance vkCreateInstance; // Instance functions. PFN_vkDestroyInstance vkDestroyInstance; PFN_vkCreateDevice vkCreateDevice; PFN_vkCreateDebugReportCallbackEXT vkCreateDebugReportCallbackEXT; PFN_vkDestroyDebugReportCallbackEXT vkDestroyDebugReportCallbackEXT; PFN_vkEnumeratePhysicalDevices vkEnumeratePhysicalDevices; PFN_vkDestroySurfaceKHR vkDestroySurfaceKHR; PFN_vkEnumerateDeviceExtensionProperties vkEnumerateDeviceExtensionProperties; #ifdef VK_USE_PLATFORM_XCB_KHR PFN_vkCreateXcbSurfaceKHR vkCreateXcbSurfaceKHR; #endif #ifdef VK_USE_PLATFORM_WAYLAND_KHR PFN_vkCreateWaylandSurfaceKHR vkCreateWaylandSurfaceKHR; #endif #ifdef VK_USE_PLATFORM_XLIB_XRANDR_EXT PFN_vkAcquireXlibDisplayEXT vkAcquireXlibDisplayEXT; PFN_vkReleaseDisplayEXT vkReleaseDisplayEXT; PFN_vkGetRandROutputDisplayEXT vkGetRandROutputDisplayEXT; #endif #if defined(VK_USE_PLATFORM_XLIB_XRANDR_EXT) || defined(VK_USE_PLATFORM_DISPLAY_KHR) PFN_vkCreateDisplayPlaneSurfaceKHR vkCreateDisplayPlaneSurfaceKHR; PFN_vkGetDisplayPlaneCapabilitiesKHR vkGetDisplayPlaneCapabilitiesKHR; PFN_vkGetPhysicalDeviceDisplayPropertiesKHR vkGetPhysicalDeviceDisplayPropertiesKHR; PFN_vkGetPhysicalDeviceDisplayPlanePropertiesKHR vkGetPhysicalDeviceDisplayPlanePropertiesKHR; PFN_vkGetDisplayModePropertiesKHR vkGetDisplayModePropertiesKHR; #endif #ifdef VK_USE_PLATFORM_ANDROID_KHR PFN_vkCreateAndroidSurfaceKHR vkCreateAndroidSurfaceKHR; #endif #ifdef VK_USE_PLATFORM_WIN32_KHR PFN_vkCreateWin32SurfaceKHR vkCreateWin32SurfaceKHR; #endif // Physical device functions. PFN_vkGetPhysicalDeviceMemoryProperties vkGetPhysicalDeviceMemoryProperties; PFN_vkGetPhysicalDeviceQueueFamilyProperties vkGetPhysicalDeviceQueueFamilyProperties; PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties; PFN_vkGetPhysicalDeviceProperties2 vkGetPhysicalDeviceProperties2; PFN_vkGetPhysicalDeviceFeatures2 vkGetPhysicalDeviceFeatures2; PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR vkGetPhysicalDeviceSurfaceCapabilitiesKHR; PFN_vkGetPhysicalDeviceSurfaceFormatsKHR vkGetPhysicalDeviceSurfaceFormatsKHR; PFN_vkGetPhysicalDeviceSurfacePresentModesKHR vkGetPhysicalDeviceSurfacePresentModesKHR; PFN_vkGetPhysicalDeviceSurfaceSupportKHR vkGetPhysicalDeviceSurfaceSupportKHR; PFN_vkGetPhysicalDeviceFormatProperties vkGetPhysicalDeviceFormatProperties; PFN_vkGetPhysicalDeviceImageFormatProperties2 vkGetPhysicalDeviceImageFormatProperties2; // Device functions. PFN_vkGetDeviceProcAddr vkGetDeviceProcAddr; PFN_vkDestroyDevice vkDestroyDevice; PFN_vkDeviceWaitIdle vkDeviceWaitIdle; PFN_vkAllocateMemory vkAllocateMemory; PFN_vkFreeMemory vkFreeMemory; PFN_vkMapMemory vkMapMemory; PFN_vkUnmapMemory vkUnmapMemory; PFN_vkGetMemoryFdKHR vkGetMemoryFdKHR; #ifdef VK_USE_PLATFORM_ANDROID_KHR PFN_vkGetMemoryAndroidHardwareBufferANDROID vkGetMemoryAndroidHardwareBufferANDROID; PFN_vkGetAndroidHardwareBufferPropertiesANDROID vkGetAndroidHardwareBufferPropertiesANDROID; #endif #ifdef VK_USE_PLATFORM_WIN32_KHR PFN_vkGetMemoryWin32HandleKHR vkGetMemoryWin32HandleKHR; #endif PFN_vkCreateBuffer vkCreateBuffer; PFN_vkDestroyBuffer vkDestroyBuffer; PFN_vkBindBufferMemory vkBindBufferMemory; PFN_vkGetBufferMemoryRequirements vkGetBufferMemoryRequirements; PFN_vkFlushMappedMemoryRanges vkFlushMappedMemoryRanges; PFN_vkCreateImage vkCreateImage; PFN_vkGetImageMemoryRequirements vkGetImageMemoryRequirements; PFN_vkGetImageMemoryRequirements2 vkGetImageMemoryRequirements2; PFN_vkBindImageMemory vkBindImageMemory; PFN_vkDestroyImage vkDestroyImage; PFN_vkCreateImageView vkCreateImageView; PFN_vkDestroyImageView vkDestroyImageView; PFN_vkCreateSampler vkCreateSampler; PFN_vkDestroySampler vkDestroySampler; PFN_vkCreateShaderModule vkCreateShaderModule; PFN_vkDestroyShaderModule vkDestroyShaderModule; PFN_vkCreateCommandPool vkCreateCommandPool; PFN_vkDestroyCommandPool vkDestroyCommandPool; PFN_vkAllocateCommandBuffers vkAllocateCommandBuffers; PFN_vkBeginCommandBuffer vkBeginCommandBuffer; PFN_vkCmdPipelineBarrier vkCmdPipelineBarrier; PFN_vkCmdBeginRenderPass vkCmdBeginRenderPass; PFN_vkCmdSetScissor vkCmdSetScissor; PFN_vkCmdSetViewport vkCmdSetViewport; PFN_vkCmdClearColorImage vkCmdClearColorImage; PFN_vkCmdEndRenderPass vkCmdEndRenderPass; PFN_vkCmdBindDescriptorSets vkCmdBindDescriptorSets; PFN_vkCmdBindPipeline vkCmdBindPipeline; PFN_vkCmdBindVertexBuffers vkCmdBindVertexBuffers; PFN_vkCmdBindIndexBuffer vkCmdBindIndexBuffer; PFN_vkCmdDraw vkCmdDraw; PFN_vkCmdDrawIndexed vkCmdDrawIndexed; PFN_vkCmdDispatch vkCmdDispatch; PFN_vkCmdCopyBufferToImage vkCmdCopyBufferToImage; PFN_vkCmdCopyImageToBuffer vkCmdCopyImageToBuffer; PFN_vkEndCommandBuffer vkEndCommandBuffer; PFN_vkFreeCommandBuffers vkFreeCommandBuffers; PFN_vkCreateRenderPass vkCreateRenderPass; PFN_vkDestroyRenderPass vkDestroyRenderPass; PFN_vkCreateFramebuffer vkCreateFramebuffer; PFN_vkDestroyFramebuffer vkDestroyFramebuffer; PFN_vkCreatePipelineCache vkCreatePipelineCache; PFN_vkDestroyPipelineCache vkDestroyPipelineCache; PFN_vkResetDescriptorPool vkResetDescriptorPool; PFN_vkCreateDescriptorPool vkCreateDescriptorPool; PFN_vkDestroyDescriptorPool vkDestroyDescriptorPool; PFN_vkAllocateDescriptorSets vkAllocateDescriptorSets; PFN_vkFreeDescriptorSets vkFreeDescriptorSets; PFN_vkCreateComputePipelines vkCreateComputePipelines; PFN_vkCreateGraphicsPipelines vkCreateGraphicsPipelines; PFN_vkDestroyPipeline vkDestroyPipeline; PFN_vkCreatePipelineLayout vkCreatePipelineLayout; PFN_vkDestroyPipelineLayout vkDestroyPipelineLayout; PFN_vkCreateDescriptorSetLayout vkCreateDescriptorSetLayout; PFN_vkUpdateDescriptorSets vkUpdateDescriptorSets; PFN_vkDestroyDescriptorSetLayout vkDestroyDescriptorSetLayout; PFN_vkGetDeviceQueue vkGetDeviceQueue; PFN_vkQueueSubmit vkQueueSubmit; PFN_vkQueueWaitIdle vkQueueWaitIdle; PFN_vkCreateSemaphore vkCreateSemaphore; PFN_vkDestroySemaphore vkDestroySemaphore; PFN_vkCreateFence vkCreateFence; PFN_vkWaitForFences vkWaitForFences; PFN_vkGetFenceStatus vkGetFenceStatus; PFN_vkDestroyFence vkDestroyFence; PFN_vkResetFences vkResetFences; PFN_vkCreateSwapchainKHR vkCreateSwapchainKHR; PFN_vkDestroySwapchainKHR vkDestroySwapchainKHR; PFN_vkGetSwapchainImagesKHR vkGetSwapchainImagesKHR; PFN_vkAcquireNextImageKHR vkAcquireNextImageKHR; PFN_vkQueuePresentKHR vkQueuePresentKHR; #ifdef VK_USE_PLATFORM_WIN32_KHR PFN_vkImportSemaphoreWin32HandleKHR vkImportSemaphoreWin32HandleKHR; PFN_vkImportFenceWin32HandleKHR vkImportFenceWin32HandleKHR; #else PFN_vkImportSemaphoreFdKHR vkImportSemaphoreFdKHR; PFN_vkGetSemaphoreFdKHR vkGetSemaphoreFdKHR; PFN_vkImportFenceFdKHR vkImportFenceFdKHR; PFN_vkGetFenceFdKHR vkGetFenceFdKHR; #endif PFN_vkGetPastPresentationTimingGOOGLE vkGetPastPresentationTimingGOOGLE; // clang-format on }; struct vk_buffer { VkBuffer handle; VkDeviceMemory memory; uint32_t size; void *data; }; /* * * String helper functions. * */ const char * vk_result_string(VkResult code); const char * vk_color_format_string(VkFormat code); const char * vk_present_mode_string(VkPresentModeKHR code); const char * vk_power_state_string(VkDisplayPowerStateEXT code); const char * vk_color_space_string(VkColorSpaceKHR code); /* * * Function and helpers. * */ #define VK_TRACE(d, ...) U_LOG_IFL_T(d->ll, __VA_ARGS__) #define VK_DEBUG(d, ...) U_LOG_IFL_D(d->ll, __VA_ARGS__) #define VK_INFO(d, ...) U_LOG_IFL_I(d->ll, __VA_ARGS__) #define VK_WARN(d, ...) U_LOG_IFL_W(d->ll, __VA_ARGS__) #define VK_ERROR(d, ...) U_LOG_IFL_E(d->ll, __VA_ARGS__) /*! * @brief Check a Vulkan VkResult, writing an error to the log and returning true if not VK_SUCCESS * * @param fun a string literal with the name of the Vulkan function, for logging purposes. * @param res a VkResult from that function. * @param file a string literal with the source code filename, such as from __FILE__ * @param line a source code line number, such as from __LINE__ * * @see vk_check_error, vk_check_error_with_free which wrap this for easier usage. * * @ingroup aux_vk */ bool vk_has_error(VkResult res, const char *fun, const char *file, int line); /*! * @def vk_check_error * @brief Perform checking of a Vulkan result, returning in case it is not VK_SUCCESS. * * @param fun A string literal with the name of the Vulkan function, for logging purposes. * @param res a VkResult from that function. * @param ret value to return, if any, upon error * * @see vk_has_error which is wrapped by this macro * * @ingroup aux_vk */ #define vk_check_error(fun, res, ret) \ do { \ if (vk_has_error(res, fun, __FILE__, __LINE__)) \ return ret; \ } while (0) /*! * @def vk_check_error_with_free * @brief Perform checking of a Vulkan result, freeing an allocation and returning in case it is not VK_SUCCESS. * * @param fun A string literal with the name of the Vulkan function, for logging purposes. * @param res a VkResult from that function. * @param ret value to return, if any, upon error * @param to_free expression to pass to `free()` upon error * * @see vk_has_error which is wrapped by this macro * * @ingroup aux_vk */ #define vk_check_error_with_free(fun, res, ret, to_free) \ do { \ if (vk_has_error(res, fun, __FILE__, __LINE__)) { \ free(to_free); \ return ret; \ } \ } while (0) /*! * @ingroup aux_vk */ VkResult vk_get_loader_functions(struct vk_bundle *vk, PFN_vkGetInstanceProcAddr g); /*! * @ingroup aux_vk */ VkResult vk_get_instance_functions(struct vk_bundle *vk); /*! * @brief Initialize mutexes in the @ref vk_bundle. * * Not required for all uses, but a precondition for some. * * @ingroup aux_vk */ VkResult vk_init_mutex(struct vk_bundle *vk); /*! * @brief De-initialize mutexes in the @ref vk_bundle. * @ingroup aux_vk */ VkResult vk_deinit_mutex(struct vk_bundle *vk); /*! * @ingroup aux_vk */ VkResult vk_init_cmd_pool(struct vk_bundle *vk); /*! * Used to enable device features as a argument @ref vk_create_device. * * @ingroup aux_vk */ struct vk_device_features { bool shader_storage_image_write_without_format; bool null_descriptor; }; /*! * @ingroup aux_vk */ VkResult vk_create_device(struct vk_bundle *vk, int forced_index, bool only_compute, VkQueueGlobalPriorityEXT global_priorty, const char *const *required_device_extensions, size_t num_required_device_extensions, const char *const *optional_device_extensions, size_t num_optional_device_extension, const struct vk_device_features *optional_device_features); /*! * Initialize a bundle with objects given to us by client code, * used by @ref client_vk_compositor in @ref comp_client. * * @ingroup aux_vk */ VkResult vk_init_from_given(struct vk_bundle *vk, PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr, VkInstance instance, VkPhysicalDevice physical_device, VkDevice device, uint32_t queue_family_index, uint32_t queue_index); /*! * @ingroup aux_vk */ bool vk_get_memory_type(struct vk_bundle *vk, uint32_t type_bits, VkMemoryPropertyFlags memory_props, uint32_t *out_type_id); /*! * Allocate memory for an image and bind it to that image. * * Handles the following steps: * * - calling vkGetImageMemoryRequirements * - comparing against the max_size * - getting the memory type (as dictated by the VkMemoryRequirements and * VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) * - calling vkAllocateMemory * - calling vkBindImageMemory * - calling vkDestroyMemory in case of an error. * * If this fails, it cleans up the VkDeviceMemory. * * @param vk Vulkan bundle * @param image The VkImage to allocate for and bind. * @param max_size The maximum value you'll allow for * VkMemoryRequirements::size. Pass SIZE_MAX if you will accept any size * that works. * @param pNext_for_allocate (Optional) a pointer to use in the pNext chain of * VkMemoryAllocateInfo. * @param out_mem Output parameter: will be set to the allocated memory if * everything succeeds. Not modified if there is an error. * @param out_size (Optional) pointer to receive the value of * VkMemoryRequirements::size. * * If this fails, you may want to destroy your VkImage as well, since this * routine is usually used in combination with vkCreateImage. * * @ingroup aux_vk */ VkResult vk_alloc_and_bind_image_memory(struct vk_bundle *vk, VkImage image, size_t max_size, const void *pNext_for_allocate, VkDeviceMemory *out_mem, VkDeviceSize *out_size); /*! * * @brief Creates a Vulkan device memory and image from a native graphics buffer handle. * * In case of error, ownership is never transferred and the caller should close the handle themselves. * * In case of success, the underlying Vulkan functionality's ownership semantics apply: ownership of the @p image_native * handle may have transferred, a reference may have been added, or the Vulkan objects may rely on the caller to keep * the native handle alive until the Vulkan objects are destroyed. Which option applies depends on the particular native * handle type used. * * See the corresponding specification texts: * * - Windows: * https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkImportMemoryWin32HandleInfoKHR * - Linux: https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkImportMemoryFdInfoKHR * - Android: * https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VkImportAndroidHardwareBufferInfoANDROID * * @ingroup aux_vk */ VkResult vk_create_image_from_native(struct vk_bundle *vk, const struct xrt_swapchain_create_info *info, struct xrt_image_native *image_native, VkImage *out_image, VkDeviceMemory *out_mem); /*! * @brief Creates a Vulkan fence from a native graphics sync handle. * * In case of error, ownership is never transferred and the caller should close the handle themselves. * * In case of success, the underlying Vulkan functionality's ownership semantics apply: ownership of the @p native * handle may have transferred, a reference may have been added, or the Vulkan object may rely on the caller to keep the * native handle alive until the Vulkan object is destroyed. Which option applies depends on the particular native * handle type used. * * See the corresponding Vulkan specification text: * https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#synchronization-fences-importing * * @ingroup aux_vk */ VkResult vk_create_fence_sync_from_native(struct vk_bundle *vk, xrt_graphics_sync_handle_t native, VkFence *out_fence); /*! * @brief Creates a Vulkan semaphore from a native graphics sync handle. * * In case of error, ownership is never transferred and the caller should close the handle themselves. * * In case of success, the underlying Vulkan functionality's ownership semantics apply: ownership of the @p native * handle may have transferred, a reference may have been added, or the Vulkan object may rely on the caller to keep the * native handle alive until the Vulkan object is destroyed. Which option applies depends on the particular native * handle type used. * * @ingroup aux_vk */ VkResult vk_create_semaphore_from_native(struct vk_bundle *vk, xrt_graphics_sync_handle_t native, VkSemaphore *out_sem); /*! * @ingroup aux_vk */ VkResult vk_create_image_simple(struct vk_bundle *vk, VkExtent2D extent, VkFormat format, VkImageUsageFlags usage, VkDeviceMemory *out_mem, VkImage *out_image); /*! * @ingroup aux_vk */ VkResult vk_create_sampler(struct vk_bundle *vk, VkSamplerAddressMode clamp_mode, VkSampler *out_sampler); /*! * @ingroup aux_vk */ VkResult vk_create_view(struct vk_bundle *vk, VkImage image, VkFormat format, VkImageSubresourceRange subresource_range, VkImageView *out_view); /*! * @ingroup aux_vk */ VkResult vk_create_view_swizzle(struct vk_bundle *vk, VkImage image, VkFormat format, VkImageSubresourceRange subresource_range, VkComponentMapping components, VkImageView *out_view); /*! * @pre Requires successful call to vk_init_mutex * @ingroup aux_vk */ VkResult vk_init_cmd_buffer(struct vk_bundle *vk, VkCommandBuffer *out_cmd_buffer); /*! * @pre Requires successful call to vk_init_mutex * @ingroup aux_vk */ VkResult vk_set_image_layout(struct vk_bundle *vk, VkCommandBuffer cmd_buffer, VkImage image, VkAccessFlags src_access_mask, VkAccessFlags dst_access_mask, VkImageLayout old_layout, VkImageLayout new_layout, VkImageSubresourceRange subresource_range); /*! * @pre Requires successful call to vk_init_mutex * @ingroup aux_vk */ VkResult vk_submit_cmd_buffer(struct vk_bundle *vk, VkCommandBuffer cmd_buffer); VkAccessFlags vk_get_access_flags(VkImageLayout layout); VkAccessFlags vk_swapchain_access_flags(enum xrt_swapchain_usage_bits bits); /*! * Always adds `VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT` and * `VK_IMAGE_USAGE_SAMPLED_BIT` to color formats so they can be used by the * compositor and client. */ VkImageUsageFlags vk_swapchain_usage_flags(struct vk_bundle *vk, VkFormat format, enum xrt_swapchain_usage_bits bits); bool vk_init_descriptor_pool(struct vk_bundle *vk, const VkDescriptorPoolSize *pool_sizes, uint32_t pool_size_count, uint32_t set_count, VkDescriptorPool *out_descriptor_pool); bool vk_allocate_descriptor_sets(struct vk_bundle *vk, VkDescriptorPool descriptor_pool, uint32_t count, const VkDescriptorSetLayout *set_layout, VkDescriptorSet *sets); bool vk_buffer_init(struct vk_bundle *vk, VkDeviceSize size, VkBufferUsageFlags usage, VkMemoryPropertyFlags properties, VkBuffer *out_buffer, VkDeviceMemory *out_mem); void vk_buffer_destroy(struct vk_buffer *self, struct vk_bundle *vk); bool vk_update_buffer(struct vk_bundle *vk, float *buffer, size_t buffer_size, VkDeviceMemory memory); /*! * @pre Requires successful call to vk_init_mutex * @ingroup aux_vk */ VkResult vk_locked_submit(struct vk_bundle *vk, VkQueue queue, uint32_t count, const VkSubmitInfo *infos, VkFence fence); #ifdef __cplusplus } #endif
33.360374
123
0.742284
81886774bd61f491cc7edab86908e5c1efe2ded2
798
h
C
System/Library/PrivateFrameworks/UIKitCore.framework/_UIKBRTDecayingOffset.h
lechium/tvOS124Headers
11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475
[ "MIT" ]
4
2019-08-27T18:03:47.000Z
2021-09-18T06:29:00.000Z
System/Library/PrivateFrameworks/UIKitCore.framework/_UIKBRTDecayingOffset.h
lechium/tvOS124Headers
11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475
[ "MIT" ]
null
null
null
System/Library/PrivateFrameworks/UIKitCore.framework/_UIKBRTDecayingOffset.h
lechium/tvOS124Headers
11d1b56dd4c0ffd88b9eac43f87a5fd6f7228475
[ "MIT" ]
null
null
null
/* * This header is generated by classdump-dyld 1.0 * on Saturday, August 24, 2019 at 9:50:53 PM Mountain Standard Time * Operating System: Version 12.4 (Build 16M568) * Image Source: /System/Library/PrivateFrameworks/UIKitCore.framework/UIKitCore * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. */ #import <UIKitCore/UIKitCore-Structs.h> #import <UIKitCore/_UIKBRTDecayingObject.h> @interface _UIKBRTDecayingOffset : _UIKBRTDecayingObject { BOOL _limitMovement; CGPoint _offset; } @property (nonatomic,readonly) CGPoint offset; @property (nonatomic,readonly) CGPoint originalOffset; -(void)reset; -(CGPoint)offset; -(id)initWithTimeoutDuration:(double)arg1 limitMovement:(BOOL)arg2 ; -(void)updateOffsetTo:(CGPoint)arg1 ; -(CGPoint)originalOffset; @end
28.5
81
0.781955
54aaf9dcb96a61acb74f423c748e4487b1caee66
1,614
h
C
TPNetworking/Classes/Base/TPNetworkPrivate.h
Topredator/TPNetworking
ad8cbbe73bb64ca6e4a421e94819814645a8746b
[ "MIT" ]
null
null
null
TPNetworking/Classes/Base/TPNetworkPrivate.h
Topredator/TPNetworking
ad8cbbe73bb64ca6e4a421e94819814645a8746b
[ "MIT" ]
null
null
null
TPNetworking/Classes/Base/TPNetworkPrivate.h
Topredator/TPNetworking
ad8cbbe73bb64ca6e4a421e94819814645a8746b
[ "MIT" ]
null
null
null
// // TPNetworkPrivate.h // TPNetwork // // Created by Topredator on 2020/10/25. // #import <CocoaLumberjack/CocoaLumberjack.h> /********************* JSON操作 ***************************/ #define TPNetworkJSONData(obj) [NSJSONSerialization dataWithJSONObject:(obj) options:NSJSONWritingPrettyPrinted error:nil] #define TPNetworkJSONString(obj) [[NSString alloc] initWithData:TPNetworkJSONData(obj) encoding:NSUTF8StringEncoding] #ifdef DEBUG static const int ddLogLevel = DDLogLevelVerbose; #else static const int ddLogLevel = DDLogLevelInfo; #endif #define TPLogError(level, frmt, ...) \ LOG_MAYBE(NO, (level & LOG_LEVEL_DEF), DDLogFlagError, 0, nil, __PRETTY_FUNCTION__, frmt, ##__VA_ARGS__) #define TPLogWarn(level, frmt, ...) \ LOG_MAYBE(LOG_ASYNC_ENABLED, (level & LOG_LEVEL_DEF), DDLogFlagWarning, 0, nil, __PRETTY_FUNCTION__, frmt, ##__VA_ARGS__) #define TPLogInfo(level, frmt, ...) \ LOG_MAYBE(LOG_ASYNC_ENABLED, (level & LOG_LEVEL_DEF), DDLogFlagInfo, 0, nil, __PRETTY_FUNCTION__, frmt, ##__VA_ARGS__) #define TPLogDebug(level, frmt, ...) \ LOG_MAYBE(LOG_ASYNC_ENABLED, (level & LOG_LEVEL_DEF), DDLogFlagDebug, 0, nil, __PRETTY_FUNCTION__, frmt, ##__VA_ARGS__) #define TPLogVerbose(level, frmt, ...) \ LOG_MAYBE(LOG_ASYNC_ENABLED, (level & LOG_LEVEL_DEF), DDLogFlagVerbose, 0, nil, __PRETTY_FUNCTION__, frmt, ##__VA_ARGS__) #import "TPHttpTask.h" @interface TPHttpTask () @property (nonatomic, strong, readwrite) NSURL *requestURL; @property (nonatomic, strong, readwrite) NSError *networkError; @property (nonatomic, strong, readwrite) NSURLSessionDataTask *sessionTask; @end
40.35
123
0.741636
54b2246aeb24717b3afc256278ee18ed96622f60
4,069
c
C
gnutls/nettle/ecc-add-jjj.c
TheShellLand/crossover-source
247b5591f1b059b95553352adb56c45b775c0c24
[ "MIT" ]
null
null
null
gnutls/nettle/ecc-add-jjj.c
TheShellLand/crossover-source
247b5591f1b059b95553352adb56c45b775c0c24
[ "MIT" ]
null
null
null
gnutls/nettle/ecc-add-jjj.c
TheShellLand/crossover-source
247b5591f1b059b95553352adb56c45b775c0c24
[ "MIT" ]
null
null
null
/* ecc-add-jjj.c Copyright (C) 2013 Niels Möller This file is part of GNU Nettle. GNU Nettle is free software: you can redistribute it and/or modify it under the terms of either: * the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. or * the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. or both in parallel, as here. GNU Nettle is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received copies of the GNU General Public License and the GNU Lesser General Public License along with this program. If not, see http://www.gnu.org/licenses/. */ /* Development of Nettle's ECC support was funded by the .SE Internet Fund. */ #if HAVE_CONFIG_H # include "config.h" #endif #include "ecc.h" #include "ecc-internal.h" void ecc_add_jjj (const struct ecc_curve *ecc, mp_limb_t *r, const mp_limb_t *p, const mp_limb_t *q, mp_limb_t *scratch) { /* Formulas, from djb, http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#addition-add-2007-bl: Computation Operation Live variables Z1Z1 = Z1^2 sqr Z1Z1 Z2Z2 = Z2^2 sqr Z1Z1, Z2Z2 U1 = X1*Z2Z2 mul Z1Z1, Z2Z2, U1 U2 = X2*Z1Z1 mul Z1Z1, Z2Z2, U1, U2 H = U2-U1 Z1Z1, Z2Z2, U1, H Z3 = ((Z1+Z2)^2-Z1Z1-Z2Z2)*H sqr, mul Z1Z1, Z2Z2, U1, H S1 = Y1*Z2*Z2Z2 mul, mul Z1Z1, U1, H, S1 S2 = Y2*Z1*Z1Z1 mul, mul U1, H, S1, S2 W = 2*(S2-S1) (djb: r) U1, H, S1, W I = (2*H)^2 sqr U1, H, S1, W, I J = H*I mul U1, S1, W, J, V V = U1*I mul S1, W, J, V X3 = W^2-J-2*V sqr S1, W, J, V Y3 = W*(V-X3)-2*S1*J mul, mul */ mp_limb_t *z1z1 = scratch; mp_limb_t *z2z2 = scratch + ecc->p.size; mp_limb_t *u1 = scratch + 2*ecc->p.size; mp_limb_t *u2 = scratch + 3*ecc->p.size; mp_limb_t *s1 = scratch; /* overlap z1z1 */ mp_limb_t *s2 = scratch + ecc->p.size; /* overlap z2z2 */ mp_limb_t *i = scratch + 4*ecc->p.size; mp_limb_t *j = scratch + 5*ecc->p.size; mp_limb_t *v = scratch + 6*ecc->p.size; /* z1^2, z2^2, u1 = x1 x2^2, u2 = x2 z1^2 - u1 */ ecc_mod_sqr (&ecc->p, z1z1, p + 2*ecc->p.size); ecc_mod_sqr (&ecc->p, z2z2, q + 2*ecc->p.size); ecc_mod_mul (&ecc->p, u1, p, z2z2); ecc_mod_mul (&ecc->p, u2, q, z1z1); ecc_mod_sub (&ecc->p, u2, u2, u1); /* Store h in u2 */ /* z3, use i, j, v as scratch, result at i. */ ecc_mod_add (&ecc->p, i, p + 2*ecc->p.size, q + 2*ecc->p.size); ecc_mod_sqr (&ecc->p, v, i); ecc_mod_sub (&ecc->p, v, v, z1z1); ecc_mod_sub (&ecc->p, v, v, z2z2); ecc_mod_mul (&ecc->p, i, v, u2); /* Delayed write, to support in-place operation. */ /* s1 = y1 z2^3, s2 = y2 z1^3, scratch at j and v */ ecc_mod_mul (&ecc->p, j, z1z1, p + 2*ecc->p.size); /* z1^3 */ ecc_mod_mul (&ecc->p, v, z2z2, q + 2*ecc->p.size); /* z2^3 */ ecc_mod_mul (&ecc->p, s1, p + ecc->p.size, v); ecc_mod_mul (&ecc->p, v, j, q + ecc->p.size); ecc_mod_sub (&ecc->p, s2, v, s1); ecc_mod_mul_1 (&ecc->p, s2, s2, 2); /* Store z3 */ mpn_copyi (r + 2*ecc->p.size, i, ecc->p.size); /* i, j, v */ ecc_mod_sqr (&ecc->p, i, u2); ecc_mod_mul_1 (&ecc->p, i, i, 4); ecc_mod_mul (&ecc->p, j, u2, i); ecc_mod_mul (&ecc->p, v, u1, i); /* now, u1, u2 and i are free for reuse .*/ /* x3, use u1, u2 as scratch */ ecc_mod_sqr (&ecc->p, u1, s2); ecc_mod_sub (&ecc->p, r, u1, j); ecc_mod_submul_1 (&ecc->p, r, v, 2); /* y3 */ ecc_mod_mul (&ecc->p, u1, s1, j); /* Frees j */ ecc_mod_sub (&ecc->p, u2, v, r); /* Frees v */ ecc_mod_mul (&ecc->p, i, s2, u2); ecc_mod_submul_1 (&ecc->p, i, u1, 2); mpn_copyi (r + ecc->p.size, i, ecc->p.size); }
33.628099
91
0.598427
60f8f792da1c194872e749f3d3fedb8870cbd776
1,349
h
C
src/ast/parser.h
winksaville/verona
7288ea4d4e71599931522f694792e8ebc9e4f409
[ "MIT" ]
null
null
null
src/ast/parser.h
winksaville/verona
7288ea4d4e71599931522f694792e8ebc9e4f409
[ "MIT" ]
null
null
null
src/ast/parser.h
winksaville/verona
7288ea4d4e71599931522f694792e8ebc9e4f409
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include "ast.h" #include "err.h" namespace parser { peg::parser create(const std::string& file, err::Errors& err); ast::Ast parse(peg::parser& parser, const std::string& file, err::Errors& err); ast::Ast parse( peg::parser& parser, const std::string& path, const std::string& ext, err::Errors& err); template<typename T> peg::parser create(const T& grammar, const std::string& file, err::Errors& err) { peg::parser parser; parser.log = [&](size_t ln, size_t col, const std::string& msg) { err << file << ":" << ln << ":" << col << ": " << msg << err::end; }; if (!parser.load_grammar(grammar.data(), grammar.size())) return {}; parser.log = nullptr; parser.enable_packrat_parsing(); parser.enable_ast<ast::AstImpl>(); return parser; } template<typename T> ast::Ast parse( peg::parser& parser, const T& src, const std::string& file, err::Errors& err) { ast::Ast ast; parser.log = [&](size_t ln, size_t col, const std::string& msg) { err << file << ":" << ln << ":" << col << ": " << msg << err::end; }; if (!parser.parse_n(src.data(), src.size(), ast, file.c_str())) return {}; return ast; } }
22.864407
72
0.584878
8e92e4de5a56cf7356a95b866377b6c159cefce0
246
h
C
EventHandler.h
algisB/kep
e0247a68cb2d9135a0986cecbe5cbac4e3dac9df
[ "MIT" ]
null
null
null
EventHandler.h
algisB/kep
e0247a68cb2d9135a0986cecbe5cbac4e3dac9df
[ "MIT" ]
null
null
null
EventHandler.h
algisB/kep
e0247a68cb2d9135a0986cecbe5cbac4e3dac9df
[ "MIT" ]
null
null
null
#pragma once #include "Event.h" using namespace std; class EventHandler { public: //vector<Event> m_events; vector<Event> m_events; EventHandler(); ~EventHandler(); Event * getEvent(EventType _eventType); void update(); };
15.375
41
0.678862
c267defc198e83061fcf7872a738ca0f7203c409
7,824
c
C
DayZ-SA-Tomato/addons/DayZ-SA-Tomato/scripts/5_Mission/core/modules/GUI/AdminMenuTeleport.c
SirFrostingham/DZMods
0374cdab0f4fee439fb698b1d9590192eb13a08a
[ "MIT" ]
null
null
null
DayZ-SA-Tomato/addons/DayZ-SA-Tomato/scripts/5_Mission/core/modules/GUI/AdminMenuTeleport.c
SirFrostingham/DZMods
0374cdab0f4fee439fb698b1d9590192eb13a08a
[ "MIT" ]
null
null
null
DayZ-SA-Tomato/addons/DayZ-SA-Tomato/scripts/5_Mission/core/modules/GUI/AdminMenuTeleport.c
SirFrostingham/DZMods
0374cdab0f4fee439fb698b1d9590192eb13a08a
[ "MIT" ]
null
null
null
/* DayZ SA Tomato Gui Admin tool for DayZ Standalone. Contact DayZ-SA-Tomato@Primary-Network.de Copyright (C) 2018 DayZ-SA-Tomato This file is part of DayZ SA Tomato. DayZ SA Tomato is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. DayZ SA Tomato is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with DayZ SA Tomato. If not, see <https://www.gnu.org/licenses/>. */ class AdminMenuGuiTeleport extends ScriptedWidgetEventHandler { protected Widget m_Root; protected AdminMenuGui m_Menu; protected ref map<int, ref Param2<string, string>> m_TextMap; protected ButtonWidget m_btn_Teleport_Teleport; protected ButtonWidget m_btn_Teleport_Reload; protected ButtonWidget m_btn_Teleport_Add_Location; protected ButtonWidget m_btn_Teleport_Spawn_Horde; //ref AdminMenuManager adminMenuManager; EditBoxWidget m_Text_Teleport_Loacation_Name; EditBoxWidget m_editbox_Teleport_HordeCount; static ref map<string, string> m_TeleportLocations; static ref map<int, string> m_TeleportLocations_old; TextListboxWidget m_List_Teleport_Location; ref array<string> TLoacations; ref array<vector> TPos; ref HordeModule m_HordeModule; //ref AdminMenuManager AMenuM; void AdminMenuGuiTeleport( Widget parent, AdminMenuGui menu ) { m_Root = GetGame().GetWorkspace().CreateWidgets( "com\\DayZ-SA-Tomato\\scripts\\5_Mission\\core\\modules\\GUI\\Layouts\\Admin_Teleport.layout", parent ); //adminMenuManager = new AdminMenuManager(); m_HordeModule = new ref HordeModule(); m_Menu = menu; GetDayZGame().Event_OnRPC.Insert( this.ReceiveRPC ); m_TeleportLocations = new map<string, string>; m_TeleportLocations_old = new map<int, string>; m_List_Teleport_Location = TextListboxWidget.Cast( m_Root.FindAnyWidget( "List_Teleport_Location" ) ); m_Text_Teleport_Loacation_Name = EditBoxWidget.Cast( m_Root.FindAnyWidget( "Text_Teleport_Loacation_Name" ) ); m_editbox_Teleport_HordeCount = EditBoxWidget.Cast( m_Root.FindAnyWidget( "editbox_Teleport_HordeCount" ) ); m_btn_Teleport_Teleport = ButtonWidget.Cast( m_Root.FindAnyWidget( "btn_Teleport_Teleport" ) ); m_btn_Teleport_Reload = ButtonWidget.Cast( m_Root.FindAnyWidget( "btn_Teleport_Reload" ) ); m_btn_Teleport_Add_Location = ButtonWidget.Cast( m_Root.FindAnyWidget( "btn_Teleport_Add_Location" ) ); m_btn_Teleport_Spawn_Horde = ButtonWidget.Cast( m_Root.FindAnyWidget( "btn_Teleport_Spawn_Horde" ) ); //m_List_Teleport_Location.ClearItems(); //TpLocations; // for ( int i = 0; i < m_Root.Locations.Count(); i++ ) // { // m_List_Teleport_Location.AddItem( GetAdminMenu().Locations[i], NULL, 0 ); // } Print("Request Data"); GetGame().RPCSingleParam( NULL, M_RPCs.M_Admin_Menu_Teleport_RequestData, new Param1<string>(""), false, NULL ); } void MouseLeave(Widget w, Widget enterW, int x, int y) { if ( w == m_Text_Teleport_Loacation_Name ) { GetAdminMenuManager().CanClose = true; } if ( w == m_editbox_Teleport_HordeCount ) { GetAdminMenuManager().CanClose = true; } } void MouseEnter(Widget w, int x, int y ) { if ( w == m_Text_Teleport_Loacation_Name ) { GetAdminMenuManager().CanClose = false; } if ( w == m_editbox_Teleport_HordeCount ) { GetAdminMenuManager().CanClose = false; } } void DeleteTeleportLocation() { m_List_Teleport_Location.ClearItems(); } int GetHordeCount() { return m_editbox_Teleport_HordeCount.GetText().ToInt(); } void AddTeleportLocation(string name) { m_List_Teleport_Location.AddItem( name, NULL, 0 ); } void LogD(string s) { GetGame().RPCSingleParam( NULL, M_RPCs.M_Admin_Menu_Log_Debug, new Param1<string>( s ), false, NULL ); } bool Click(Widget w, int x, int y, int button) { PlayerBase player = PlayerBase.Cast( GetGame().GetPlayer() ); string TpLocation = GetCurrentSelection(); if (player) { if( ( w == m_btn_Teleport_Teleport ) ) { for (int t = 0; t < GetFileHandler().RootTeleport.Children.Count(); ++t) { if(GetFileHandler().RootTeleport.Children[t].LocationName == TpLocation) { ScriptRPC TListDst = new ScriptRPC(); TListDst.Write( GetFileHandler().RootTeleport.Children[t].LocationPos[0] ); TListDst.Write( GetFileHandler().RootTeleport.Children[t].LocationPos[2] ); TListDst.Send(NULL, M_RPCs.M_Admin_Menu_TpMeToPosVec, false, NULL); } } } if( ( w == m_btn_Teleport_Reload ) ) { GetGame().RPCSingleParam( NULL, M_RPCs.M_Admin_Menu_Teleport_RequestData, new Param1<string>(""), false, NULL ); } if( ( w == m_btn_Teleport_Add_Location ) ) { string text = m_Text_Teleport_Loacation_Name.GetText(); SendToFile(text); GetGame().RPCSingleParam( NULL, M_RPCs.M_Admin_Menu_Teleport_RequestData, new Param1<string>(""), false, NULL ); } if( ( w == m_btn_Teleport_Spawn_Horde ) ) { int HCount = GetHordeCount(); for (t = 0; t < GetFileHandler().RootTeleport.Children.Count(); ++t) { if(GetFileHandler().RootTeleport.Children[t].LocationName == TpLocation) { m_HordeModule.Spawn(GetFileHandler().RootTeleport.Children[t].LocationPos, GetHordeCount(), 50, GetCurrentSelection()) } } } } return true; } void SendToFile(string name) { ScriptRPC Adding = new ScriptRPC(); Adding.Write(name); Adding.Send(NULL, M_RPCs.M_Admin_Menu_Teleport_Write_Pre, false, NULL); } void ~AdminMenuGuiTeleport() { } void Focus() { } void AddLocationToFile(string LocationName) { } override bool OnFocus( Widget w, int x, int y ) { /* if( m_Menu ) m_Menu.OnFocus( w, x, y ); if( w ) { Param2<string, string> p = m_TextMap.Get( w.GetUserID() ); if( p ) { return true; } } return ( w != null ); */ } bool stop = false; void ReceiveRPC( PlayerIdentity sender, Object target, int rpc_type, ParamsReadContext ctx ) { int ListCount = 0; ref array<string> TLoacations = new ref array< string >; ref array<vector> TPos = new ref array< vector >; PlayerBase Admin; switch(rpc_type) { case M_RPCs.M_Admin_Menu_Teleport_ReciveData: Print("Data Recived"); ref array<string> TpName = new ref array< string >; ref array<vector> TpPos = new ref array< vector >; ctx.Read(TpName); ctx.Read(TpPos); Print("Data Count = " + TpName.Count()) if ( GetGame().IsServer() ) { } if ( GetGame().IsClient() && GetGame().IsMultiplayer() ) { m_List_Teleport_Location.ClearItems(); for ( int i = 0; i < TpName.Count(); i++ ) { TLoacations.Insert(TpName[i]) TPos.Insert(TpPos[i]) m_List_Teleport_Location.AddItem( TLoacations[i], NULL, 0 ); Print("Client - Created Child with name = " + TpName[i]); GetFileHandler().RootTeleport.AddChilds(TpName[i], TpPos[i]) } //Loadarray(); } break; } } string GetCurrentSelection() { if ( m_List_Teleport_Location.GetSelectedRow() != -1 ) { string result; m_List_Teleport_Location.GetItemText( m_List_Teleport_Location.GetSelectedRow(), 0, result ); return result; } return ""; } // void Message( string txt ) // { // GetGame().GetMission().OnEvent(ChatMessageEventTypeID, new ChatMessageEventParams(0, "", txt, "")); // } }
29.19403
159
0.690951
b060a649268503ba3d44ab77f31e695ebe4f0be2
1,191
h
C
src/controller.h
Azrrael-exe/arduino-ps4
ff3e0b2e74a84748391cd9200ac437dab67538e8
[ "MIT" ]
5
2017-12-05T08:03:09.000Z
2021-09-06T08:49:40.000Z
src/controller.h
Azrrael-exe/arduino-ps4
ff3e0b2e74a84748391cd9200ac437dab67538e8
[ "MIT" ]
null
null
null
src/controller.h
Azrrael-exe/arduino-ps4
ff3e0b2e74a84748391cd9200ac437dab67538e8
[ "MIT" ]
null
null
null
#ifndef controller_h #define controller_h #define LeftHat 0x10 #define RightHat 0x11 #include <Arduino.h> namespace controller { bool checkAxis(PS4BT &ctr){ if(ctr.getAnalogHat(LeftHatX) > 137 || ctr.getAnalogHat(LeftHatX) < 117 || ctr.getAnalogHat(LeftHatY) > 137 || ctr.getAnalogHat(LeftHatY) < 117 || ctr.getAnalogHat(RightHatX) > 137 || ctr.getAnalogHat(RightHatX) < 117 || ctr.getAnalogHat(RightHatY) > 137 || ctr.getAnalogHat(RightHatY) < 117) { return true; } else { return false; } } uint16_t readAxis(PS4BT &ctr, uint8_t axis){ uint16_t output = 0; if(axis == LeftHat){ output = (ctr.getAnalogHat(LeftHatX) << 8 | ctr.getAnalogHat(LeftHatY)); } else if(axis == RightHat){ output = (ctr.getAnalogHat(RightHatX) << 8 | ctr.getAnalogHat(RightHatY)); } return output; } uint16_t readButtonsClick(PS4BT &ctr){ uint16_t output = 0; int b_list[16] = { UP, LEFT, DOWN, RIGHT, TRIANGLE, SQUARE, CROSS, CIRCLE, L2, L1, R1, R1, SHARE, L3, R3, OPTIONS }; for(int i=0; i<16; i++){ bitWrite(output, i, ctr.getButtonClick(b_list[i])); } return output; } } #endif
27.068182
298
0.634761
f12bf49a8d9e8714208e249c7aa7ac489b371b0b
4,333
h
C
PLUTO/Src/MHD/ShearingBox/shearingbox.h
Mixpap/JetCloudSim
bc44ca3eb3956b87a4390428d897099a92a8b9b2
[ "MIT" ]
1
2018-11-21T20:32:36.000Z
2018-11-21T20:32:36.000Z
PLUTO/Src/MHD/ShearingBox/shearingbox.h
Mixpap/JetCloudSim
bc44ca3eb3956b87a4390428d897099a92a8b9b2
[ "MIT" ]
3
2018-10-08T22:20:49.000Z
2018-10-19T14:00:44.000Z
PLUTO/Src/MHD/ShearingBox/shearingbox.h
Mixpap/JetCloudSim
bc44ca3eb3956b87a4390428d897099a92a8b9b2
[ "MIT" ]
1
2019-06-26T05:37:43.000Z
2019-06-26T05:37:43.000Z
/* ///////////////////////////////////////////////////////////////////// */ /*! \file \brief Shearing-Box module header file The Shearing-Box module header file contains basic macro definitions, function prototypes and declaration of global variables used by the sheraring-box module. The variable ::sb_q and ::sb_Omega are the most important ones and \b must be defined and initialized in your init.c in order to configure your shearing-box problem. Optionally, the order of interpolation (default is 2) at physical boundaries may be changed using the ::SB_ORDER macro. The additional macros ::SB_SYMMETRIZE_HYDRO, ::SB_SYMMETRIZE_EY and ::SB_SYMMETRIZE_EZ may be set to YES/NO to enable/disable enforcement of conservation at the radial (x) boundaries. \authors A. Mignone (mignone@ph.unito.it)\n G. Muscianisi (g.muscianisi@cineca.it) \date Aug 26, 2015 \todo Check if sb_vy and sb_Ly are really needed as global variables. */ /* ///////////////////////////////////////////////////////////////////// */ /*! Sets the order of interpolation at physical boundaries (1, 2 or 3).*/ #if RECONSTRUCTION == LINEAR || RECONSTRUCTION == WENO3 || RECONSTRUCTION == LimO3 #define SB_ORDER 2 #else #define SB_ORDER 3 #endif #ifndef FARGO #ifndef SB_SYMMETRIZE_HYDRO #define SB_SYMMETRIZE_HYDRO YES /**< Symmetrize the hydrodynamical fluxes at the left and right x-boundaries in order to enforce conservation of hydrodynamic variables like density, momentum and energy (no magnetic field). Default is YES.*/ #endif #ifndef SB_SYMMETRIZE_EY #define SB_SYMMETRIZE_EY (YES && (DIMENSIONS == 3)) /**< Symmetrize the y-component of the electric field at the left and right x-boundaries to enforce conservation of magnetic field (only in 3D). */ #endif #ifndef SB_SYMMETRIZE_EZ #define SB_SYMMETRIZE_EZ YES /**< Symmetrize the z-component of electric field at the left and right x-boundaries to enforce conservation of magnetic field. */ #endif #define SB_FORCE_EMF_PERIODS NO /**< Force periodicity at y- and z- boundaries. */ #else #define SB_SYMMETRIZE_HYDRO NO #define SB_SYMMETRIZE_EY (NO && (DIMENSIONS == 3)) #define SB_SYMMETRIZE_EZ NO #define SB_FORCE_EMF_PERIODS NO #endif /* ---------------------------- Global variables ---------------------------- */ #ifndef SB_Q #define SB_Q 1.5 /**< The shear parameter, \f$\DS q = -\HALF\frac{d\log \Omega^2}{d\log R} \f$. */ #endif #ifndef SB_OMEGA #define SB_OMEGA 1.0 /**< Disk local orbital frequency \f$ \Omega_0 = \Omega(R_0)\f$. */ #endif //extern double sb_q; /**< The shear parameter, \f$\DS q = -\HALF\frac{d\log // \Omega^2}{d\log R} \f$. The explicit numerical value and the // variable definition should be set inside your Init() function. */ //extern double sb_Omega; /**< Disk local orbital frequency \f$ \Omega_0 = // \Omega(R_0)\f$. The explicit numerical value and the variable // definition should be set inside your Init() function. */ extern double sb_vy; /**< Velocity offset (>0), in SB_Boundary(). */ #define SB_A (-0.5*SB_OMEGA*SB_Q) /**< Short-hand definition for the Oort constant \f$ A = -q\Omega_0/2 \f$. */ /* *********************************************************** \cond REPEAT_FUNCTION_DOCUMENTATION_IN_HEADER_FILES Function prototyping *********************************************************** */ void SB_Boundary (const Data *, int, Grid *) ; void SB_ShearingInterp (double *, double *, double, int, Grid *); void SB_CorrectFluxes (Data_Arr, double, double, Grid *); #ifdef STAGGERED_MHD void SB_CorrectEMF (EMF *, Data_Arr, Grid *); #endif int SB_JSHIFT (int); void SB_SaveFluxes (Sweep *, Grid *); void SB_SetBoundaryVar(double ***, RBox *, int, double, Grid *); void SB_ShiftBoundaryVar(double ***, RBox *, int, double, Grid *); void SB_FillBoundaryGhost(double ***, RBox *, int, int, Grid *); #ifdef PARALLEL void ExchangeX (real *, real *, int, Grid *); #endif /* \endcond */
39.036036
82
0.604893
fc468e5ed9aa1d5f58ee4956e8b5701d649c0339
4,000
h
C
OutPutHeaders/WCDevice.h
cocos543/WeChatTimeLineRobot
1e93480e502e36ca9a21a506f481aa1fcb70ac4b
[ "MIT" ]
106
2016-04-09T01:16:14.000Z
2021-06-04T00:20:24.000Z
OutPutHeaders/WCDevice.h
cocos543/WeChatTimeLineRobot
1e93480e502e36ca9a21a506f481aa1fcb70ac4b
[ "MIT" ]
2
2017-06-13T09:41:29.000Z
2018-03-26T03:32:07.000Z
OutPutHeaders/WCDevice.h
cocos543/WeChatTimeLineRobot
1e93480e502e36ca9a21a506f481aa1fcb70ac4b
[ "MIT" ]
58
2016-04-28T09:52:08.000Z
2021-12-25T06:42:14.000Z
/** * This header is generated by class-dump-z 0.2a. * class-dump-z is Copyright (C) 2009 by KennyTM~, licensed under GPLv3. * * Source: (null) */ #import "WCDBCoding.h" #import <XXUnknownSuperclass.h> // Unknown library #import "WeChat-Structs.h" @class NSString, WCDeviceExtData; @interface WCDevice : XXUnknownSuperclass <WCDBCoding> { NSString* m_deviceType; NSString* m_deviceID; NSString* m_usrname; NSString* m_deviceName; long long m_DID; NSString* m_mac; NSString* m_md5Str; NSString* m_connProto; unsigned long m_connStrategy; unsigned long m_closeStrategy; long m_manuDataMacOffset; long m_serNumMacOffset; WCDeviceExtData* m_extData; unsigned long IntRes1; unsigned long IntRes2; NSString* StrRes1; NSString* StrRes2; long long m___rowID; } @property(assign, nonatomic) long long __rowID; @property(readonly, copy) NSString* debugDescription; @property(readonly, copy) NSString* description; @property(readonly, assign) Class superclass; @property(readonly, assign) unsigned hash; @property(retain, nonatomic) WCDeviceExtData* m_extData; @property(retain, nonatomic) NSString* StrRes2; @property(retain, nonatomic) NSString* StrRes1; @property(assign, nonatomic) unsigned long IntRes2; @property(assign, nonatomic) unsigned long IntRes1; @property(assign, nonatomic) long m_serNumMacOffset; @property(assign, nonatomic) long m_manuDataMacOffset; @property(assign, nonatomic) unsigned long m_closeStrategy; @property(assign, nonatomic) unsigned long m_connStrategy; @property(retain, nonatomic) NSString* m_connProto; @property(retain, nonatomic) NSString* m_md5Str; @property(retain, nonatomic) NSString* m_mac; @property(assign, nonatomic) long long m_DID; @property(retain, nonatomic) NSString* m_deviceName; @property(retain, nonatomic) NSString* m_usrname; @property(retain, nonatomic) NSString* m_deviceID; @property(retain, nonatomic) NSString* m_deviceType; +(id)dummyObject; -(void).cxx_destruct; -(BOOL)hasAbility:(id)ability; -(id)deviceDisplayIconUrl; -(id)deviceDisplayTitle; -(void)setupDataBeforeWriteDB; -(void)setupDataFromDB; -(BOOL)isAlwaysConnectInChatView; -(BOOL)isContinueConnectWhenExit; -(BOOL)isWeightScaleDev; -(BOOL)isPedometerDev; -(BOOL)isBleSimpleDev; -(BOOL)isM7Device; -(BOOL)isWifiDevice; -(BOOL)isBLEDevice; -(BOOL)isEADevice; -(BOOL)isBluetoohDevice; -(void)dealloc; -(id)init; -(const map<unsigned long, unsigned long, std::__1::less<unsigned long>, std::__1::allocator<std::__1::pair<const unsigned long, unsigned long> > >*)getValueTagIndexMap; -(id)getValueTypeTable; -(const map<unsigned long, unsigned long, std::__1::less<unsigned long>, std::__1::allocator<std::__1::pair<const unsigned long, unsigned long> > >*)getFileValueTagIndexMap; -(id)getFileValueTypeTable; -(const map<unsigned long, unsigned long, std::__1::less<unsigned long>, std::__1::allocator<std::__1::pair<const unsigned long, unsigned long> > >*)getPackedValueTagIndexMap; -(id)getPackedValueTypeTable; -(const map<std::__1::basic_string<char>, unsigned long, std::__1::less<std::__1::basic_string<char> >, std::__1::allocator<std::__1::pair<const std::__1::basic_string<char>, unsigned long> > >*)getValueNameIndexMap; -(id)getValueTable; -(const WCDBCondition<NSString* >*)db_StrRes2; -(const WCDBCondition<NSString* >*)db_StrRes1; -(const WCDBCondition<unsigned long>*)db_IntRes2; -(const WCDBCondition<unsigned long>*)db_IntRes1; -(const WCDBCondition<long>*)db_m_serNumMacOffset; -(const WCDBCondition<long>*)db_m_manuDataMacOffset; -(const WCDBCondition<unsigned long>*)db_m_closeStrategy; -(const WCDBCondition<unsigned long>*)db_m_connStrategy; -(const WCDBCondition<NSString* >*)db_m_connProto; -(const WCDBCondition<NSString* >*)db_m_md5Str; -(const WCDBCondition<NSString* >*)db_m_mac; -(const WCDBCondition<long long>*)db_m_DID; -(const WCDBCondition<NSString* >*)db_m_deviceName; -(const WCDBCondition<NSString* >*)db_m_usrname; -(const WCDBCondition<NSString* >*)db_m_deviceID; -(const WCDBCondition<NSString* >*)db_m_deviceType; @end
39.60396
216
0.78
52a6596af16f7b7ed8846ad396fc2fb8370e8f68
5,159
c
C
implementations/luo2013/2bwt-lib/CacheTest.c
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
6
2021-10-06T07:47:04.000Z
2022-01-25T05:09:08.000Z
implementations/luo2013/2bwt-lib/CacheTest.c
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/luo2013/2bwt-lib/CacheTest.c
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
/* CacheTest.c Testing speed of cache Copyright 2006, Wong Chi Kwong, all rights reserved. This module tests the speed of cache. This software may be used freely for any purpose. However, when distributed, the original source must be clearly stated, and, when the source code is distributed, the copyright notice must be retained and any alterations in the code must be clearly marked. No warranty is given regarding the quality of this software. */ #include <stdlib.h> #include <intrin.h> #include <mmintrin.h> #include "MiscUtilities.h" #include "MemManager.h" #include "iniparser.h" #include "r250.h" #include "Timing.h" dictionary *ParseInput(int argc, char** argv); void ValidateParameters(); unsigned int MemorySize; unsigned int NumberOfAccess; char *ReadWrite; unsigned int NumberOfIteration; int main(int argc, char** argv) { unsigned int* __restrict address; unsigned int* __restrict memory; unsigned int i, j; unsigned int t=0; unsigned int numberOfMemoryLocation; dictionary *programInput; double startTime; double elapsedTime = 0, totalElapsedTime = 0; double initializationTime, experimentTime; programInput = ParseInput(argc, argv); ValidateParameters(); // Initialize memory manager MMMasterInitialize(0, 0, FALSE, NULL); numberOfMemoryLocation = MemorySize / sizeof(int); // Allocate memory address = MMUnitAllocate((NumberOfAccess + 8) * sizeof(unsigned int)); memory = MMUnitAllocate((numberOfMemoryLocation + 32) * sizeof(unsigned int)); // Set random seed r250_init(getRandomSeed()); // Set start time startTime = setStartTime(); printf("Initialize memory pointers with random values.."); for (i=0; i<numberOfMemoryLocation + 32; i++) { memory[i] = r250(); } // Initialize address and memory for (i=0; i<NumberOfAccess + 8; i++) { address[i] = (r250() % numberOfMemoryLocation) / 4 * 4; } printf("finished.\n"); elapsedTime = getElapsedTime(startTime) - totalElapsedTime; totalElapsedTime += elapsedTime; initializationTime = elapsedTime; // Test memory speed for read if (ReadWrite[0] == 'R' || ReadWrite[0] == 'r') { for (i=0; i<NumberOfIteration; i++) { for (j=0; j<NumberOfAccess; j++) { t += memory[address[j]]; } } } // Test memory speed for write if (ReadWrite[0] == 'W' || ReadWrite[0] == 'w') { for (i=0; i<NumberOfIteration; i++) { for (j=0; j<NumberOfAccess; j++) { memory[address[j]] += address[j]; } } } elapsedTime = getElapsedTime(startTime) - totalElapsedTime; totalElapsedTime += elapsedTime; experimentTime = elapsedTime; // So that compiler does not remove code for variables t and r if (t==0) { printf("\n"); } printf("Experiment completed.\n"); printf("Initialization time = "); printElapsedTime(stdout, FALSE, FALSE, TRUE, 2, initializationTime); printf("Experiment time = "); printElapsedTime(stdout, FALSE, FALSE, TRUE, 2, experimentTime); MMUnitFree(address, (NumberOfAccess + 8) * sizeof(unsigned int)); MMUnitFree(memory, (numberOfMemoryLocation + 32) * sizeof(unsigned int)); iniparser_freedict(programInput); return 0; } dictionary *ParseInput(int argc, char** argv) { dictionary *programInput; programInput = paraparser_load(argc, argv, 0, NULL); MemorySize = iniparser_getint(programInput, "argument:1", 0); if (!MemorySize) { fprintf(stderr, "Syntax: %s <Memory size> <Number of Access> <Read/Write> <No. of iteration>\n", argv[0]); exit(1); } NumberOfAccess = iniparser_getint(programInput, "argument:2", 0); if (!NumberOfAccess) { fprintf(stderr, "Syntax: %s <Memory size> <Number of Access> <Read/Write> <No. of iteration>\n", argv[0]); exit(1); } ReadWrite = iniparser_getstring(programInput, "argument:3", 0); if (!NumberOfAccess) { fprintf(stderr, "Syntax: %s <Memory size> <Number of Access> <Read/Write> <No. of iteration>\n", argv[0]); exit(1); } NumberOfIteration = iniparser_getint(programInput, "argument:4", 0); if (!NumberOfIteration) { fprintf(stderr, "Syntax: %s <Memory size> <Number of Access> <Read/Write> <No. of iteration>\n", argv[0]); exit(1); } return programInput; } void ValidateParameters() { if (MemorySize == 0) { fprintf(stderr, "Memory Size = 0!\n"); exit(1); } if (MemorySize % 4 != 0) { fprintf(stderr, "Memory Size must be multiple of 4!\n"); exit(1); } if (NumberOfAccess == 0) { fprintf(stderr, "Number of Access = 0!\n"); exit(1); } if (ReadWrite[0] != 'R' && ReadWrite[0] != 'r' && ReadWrite[0] != 'W' && ReadWrite[0] != 'w') { fprintf(stderr, "Read/Write is invalid!\n"); exit(1); } if (NumberOfIteration == 0) { fprintf(stderr, "Number of Iteration = 0!\n"); exit(1); } }
28.038043
114
0.622601
fb5c9356b91fbe9fbfa25de863ccf22727ff2f0e
646
h
C
System/Library/PrivateFrameworks/ProactiveSupport.framework/_PASDatabaseMigrationContext.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
1
2020-11-04T15:43:01.000Z
2020-11-04T15:43:01.000Z
System/Library/PrivateFrameworks/ProactiveSupport.framework/_PASDatabaseMigrationContext.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
null
null
null
System/Library/PrivateFrameworks/ProactiveSupport.framework/_PASDatabaseMigrationContext.h
zhangkn/iOS14Header
4323e9459ed6f6f5504ecbea2710bfd6c3d7c946
[ "MIT" ]
null
null
null
/* * This header is generated by classdump-dyld 1.0 * on Sunday, September 27, 2020 at 11:42:26 AM Mountain Standard Time * Operating System: Version 14.0 (Build 18A373) * Image Source: /System/Library/PrivateFrameworks/ProactiveSupport.framework/ProactiveSupport * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. */ @protocol _PASDatabaseMigrationProtocol; @class NSObject, _PASSqliteDatabase, NSDictionary; @interface _PASDatabaseMigrationContext : NSObject { NSObject*<_PASDatabaseMigrationProtocol> object; _PASSqliteDatabase* db; unsigned version; NSDictionary* migrations; } -(id)description; @end
26.916667
93
0.795666
1cabf0fa84ce21224e72e781b2705783395bcae9
720
c
C
src/cx/alphatab.c
fildesh/fildesh
1bddffb7c521c54b4d6a49cf6533b2c75b06f1f0
[ "0BSD" ]
3
2021-12-07T20:15:38.000Z
2022-03-13T08:59:42.000Z
src/cx/alphatab.c
grencez/lace
3865f45140ad423f8c33517d647940a803e0d476
[ "0BSD" ]
40
2015-07-16T18:56:50.000Z
2021-09-01T04:46:12.000Z
src/cx/alphatab.c
grencez/lace
3865f45140ad423f8c33517d647940a803e0d476
[ "0BSD" ]
null
null
null
#include "fildesh.h" #include "alphatab.h" #include <stdio.h> Sign cmp_AlphaTab (const AlphaTab* a, const AlphaTab* b) { zuint na = a->sz; zuint nb = b->sz; int ret; if (na > 0 && !a->s[na-1]) --na; if (nb > 0 && !b->s[nb-1]) --nb; if (na <= nb) { ret = memcmp (a->s, b->s, na * sizeof(char)); if (ret == 0 && na < nb) ret = -1; } else { ret = memcmp (a->s, b->s, nb * sizeof(char)); if (ret == 0) ret = 1; } return sign_of (ret); } Sign cmp_cstr_loc (const char* const* a, const char* const* b) { return cmp_cstr (*a, *b); } void cat_uint_AlphaTab (AlphaTab* a, uint x) { char buf[50]; (void) sprintf(buf, "%u", x); cat_cstr_AlphaTab (a, buf); }
16.744186
57
0.529167
ea6e5659d306bd528bbe3e2bd62ac9537edf4882
9,566
h
C
code/modules/message/include/message/Connect.h
BrightComposite/RaptureStateToolkit
6eb3c831540ba6a9d29e903dd3c537aac2e7f91f
[ "MIT" ]
null
null
null
code/modules/message/include/message/Connect.h
BrightComposite/RaptureStateToolkit
6eb3c831540ba6a9d29e903dd3c537aac2e7f91f
[ "MIT" ]
null
null
null
code/modules/message/include/message/Connect.h
BrightComposite/RaptureStateToolkit
6eb3c831540ba6a9d29e903dd3c537aac2e7f91f
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------- #pragma once #ifndef CONNECT_H #define CONNECT_H //--------------------------------------------------------------------------- #include "Channel.h" //--------------------------------------------------------------------------- namespace asd { class Connector; //--------------------------------------------------------------------------- template<class Dst, typename Msg, useif<is_message<Msg>::value>> void connect(Connector & c, const function<void(handle<Msg> &, Dst &)> & receiver); template<class Dst, typename Msg, class RealDst, useif<is_message<Msg>::value, is_dest<RealDst, Msg>::value, based_on<RealDst, Dst>::value>> void connect(Connector & c, const function<void(handle<Msg> &, Dst &)> & receiver, RealDst & dest); //--------------------------------------------------------------------------- class BasicConnection : public shareable<BasicConnection> { public: BasicConnection(size_t id) : id(id) {} virtual ~BasicConnection() {} protected: size_t id; }; template<class Dst, typename Msg, class RealDst = empty> class Connection : public BasicConnection { public: Connection(size_t id, RealDst & dest) : BasicConnection(id), dest(dest) {} virtual ~Connection() { Channel<Dst, Msg>::disconnect(dest, id); } protected: RealDst & dest; }; template<class Dst, typename Msg> class Connection<Dst, Msg, empty> : public BasicConnection { public: Connection(size_t id) : BasicConnection(id) {} virtual ~Connection() { Channel<Dst, Msg>::disconnect(id); } }; class Connector { template<class Dst, typename Msg, used_t> friend void connect(Connector &, const function<void(handle<Msg> &, Dst &)> &); template<class Dst, typename Msg, class RealDst, used_t> friend void connect(Connector &, const function<void(handle<Msg> &, Dst &)> &, RealDst &); template<class Dst, typename Msg> void add(size_t id) { _connections.push_back(handle<Connection<Dst, Msg>>(id)); } template<class Dst, typename Msg, class RealDst> void add(size_t id, RealDst & dest) { _connections.push_back(handle<Connection<Dst, Msg, RealDst>>(id, dest)); } array_list<BasicConnection> _connections; }; //--------------------------------------------------------------------------- /** * Permanent connections (lifetime of a connection < lifetime of a receiver >= lifetime of a channel/destination) */ template<class Dst, typename Msg, typename MsgDst = message_dst_t<Dst, Msg>, useif<is_message<Msg>::value>, useif<is_same<MsgDst, Dst>::value>> void connect(const function<void(handle<Msg> &, Dst &)> & receiver) { Channel<Dst, Msg>::connect(receiver); } template<class Dst, typename Msg, typename MsgDst = message_dst_t<Dst, Msg>, useif<is_message<Msg>::value>, skipif<is_same<MsgDst, Dst>::value>, useif<is_base_of<MsgDst, Dst>::value>> void connect(const function<void(handle<Msg> &, Dst &)> & receiver) { Channel<MsgDst, Msg>::connect(make_function([&receiver](handle<Msg> & msg, MsgDst & dst) { receiver(msg, static_cast<Dst &>(dst)); })); } template<class Functor, useif<can_connect_functor<Functor>::value>, skipif<based_on<Functor, Connector>::value>> void connect(Functor & receiver) { connect(make_function(receiver)); } template<class Functor, useif<can_connect_functor<Functor>::value>, skipif<based_on<Functor, Connector>::value>> void connect(Functor && receiver) { connect(make_function(forward<Functor>(receiver))); } template<class Rcvr, class Method, useif<is_method<Rcvr, Method>::value, can_connect_method<Method>::value>, skipif<based_on<Rcvr, Connector>::value>> void connect(Rcvr receiver, Method method) { connect(make_function(receiver, method)); } template<class Dst, typename Msg, class RealDst, typename MsgDst = message_dst_t<Dst, Msg>, useif<is_message<Msg>::value, is_dest<RealDst, Msg>::value, based_on<RealDst, Dst>::value>, useif<is_same<MsgDst, Dst>::value>> void connect(const function<void(handle<Msg> &, Dst &)> & receiver, RealDst & dest) { Channel<Dst, Msg>::connect(dest, receiver); } template<class Dst, typename Msg, class RealDst, typename MsgDst = message_dst_t<Dst, Msg>, useif<is_message<Msg>::value, is_dest<RealDst, Msg>::value, based_on<RealDst, Dst>::value>, skipif<is_same<MsgDst, Dst>::value>, useif<is_base_of<MsgDst, Dst>::value>> void connect(const function<void(handle<Msg> &, Dst &)> & receiver) { Channel<MsgDst, Msg>::connect(make_function([&receiver](handle<Msg> & msg, MsgDst & dst) { receiver(msg, static_cast<Dst &>(dst)); })); } template<class Functor, class RealDst, useif<can_connect_functor<Functor, RealDst>::value>, skipif<based_on<Functor, Connector>::value>> void connect(Functor & receiver, RealDst & dest) { connect(make_function(receiver), dest); } template<class Functor, class RealDst, useif<can_connect_functor<Functor, RealDst>::value>, skipif<based_on<Functor, Connector>::value>> void connect(Functor && receiver, RealDst & dest) { connect(make_function(forward<Functor>(receiver)), dest); } template<class Rcvr, class Method, class RealDst, useif<is_method<decay_t<Rcvr>, Method>::value, can_connect_method<Method, RealDst>::value>, skipif<based_on<Rcvr, Connector>::value>> void connect(Rcvr receiver, Method method, RealDst & dest) { connect(make_function(receiver, method), dest); } //--------------------------------------------------------------------------- /** * Collectable connections (lifetime of a connection < lifetime of a receiver < lifetime of a channel/destination) */ template<class Dst, typename Msg, used_t> void connect(Connector & c, const function<void(handle<Msg> &, Dst &)> & receiver) { c.add<Dst, Msg>(Channel<Dst, Msg>::connect(receiver)); } template<class Functor, useif<can_connect_functor<Functor>::value>> void connect(Connector & c, Functor & receiver) { connect(c, make_function(receiver)); } template<class Functor, useif<can_connect_functor<Functor>::value>> void connect(Connector & c, Functor && receiver) { connect(c, make_function(forward<Functor>(receiver))); } template<class Rcvr, class Method, useif<is_method<Rcvr, Method>::value, can_connect_method<Method>::value>> void connect(Connector & c, Rcvr receiver, Method method) { connect(c, make_function(receiver, method)); } template<class Dst, typename Msg, class RealDst, used_t> void connect(Connector & c, const function<void(handle<Msg> &, Dst &)> & receiver, RealDst & dest) { c.add<Dst, Msg>(Channel<Dst, Msg>::connect(dest, receiver), dest); } template<class Functor, class RealDst, useif<can_connect_functor<Functor, RealDst>::value>> void connect(Connector & c, Functor & receiver, RealDst & dest) { connect(c, make_function(receiver), dest); } template<class Functor, class RealDst, useif<can_connect_functor<Functor, RealDst>::value>> void connect(Connector & c, Functor && receiver, RealDst & dest) { connect(c, make_function(forward<Functor>(receiver)), dest); } template<class Rcvr, class Method, class RealDst, useif<is_method<Rcvr, Method>::value, can_connect_method<Method, RealDst>::value>> void connect(Connector & c, Rcvr receiver, Method method, RealDst & dest) { connect(c, make_function(receiver, method), dest); } //--------------------------------------------------------------------------- /** * Automatic connections (lifetime of a connection = lifetime of a receiver < lifetime of a channel/destination) */ template<class Rcvr, useif<can_connect_functor<Rcvr>::value>, useif<based_on<Rcvr, Connector>::value>> void connect(Rcvr * receiver) { connect(*receiver, make_function(receiver)); } template<class Rcvr, class RealDst, useif<can_connect_functor<Rcvr, RealDst>::value>, useif<based_on<Rcvr, Connector>::value>> void connect(Rcvr * receiver, RealDst & dest) { connect(*receiver, make_function(receiver), dest); } template<class Rcvr, class Method, useif<is_method<Rcvr, Method>::value, can_connect_method<Method>::value>, useif<based_on<Rcvr, Connector>::value>> void connect(Rcvr * receiver, Method method) { connect(*receiver, make_function(receiver, method)); } template<class Rcvr, class Method, class RealDst, useif<is_method<Rcvr, Method>::value, can_connect_method<Method, RealDst>::value>, useif<based_on<Rcvr, Connector>::value>> void connect(Rcvr * receiver, Method method, RealDst & dest) { connect(*receiver, make_function(receiver, method), dest); } template<class Rcvr, useif<can_connect_functor<Rcvr>::value>, useif<based_on<Rcvr, Connector>::value>> void connect(Rcvr & receiver) { connect(receiver, make_function(receiver)); } template<class Rcvr, class RealDst, useif<can_connect_functor<Rcvr, RealDst>::value>, useif<based_on<Rcvr, Connector>::value>> void connect(Rcvr & receiver, RealDst & dest) { connect(receiver, make_function(receiver), dest); } template<class Rcvr, class Method, useif<is_method<Rcvr, Method>::value, can_connect_method<Method>::value>, useif<based_on<Rcvr, Connector>::value>> void connect(Rcvr & receiver, Method method) { connect(receiver, make_function(receiver, method)); } template<class Rcvr, class Method, class RealDst, useif<is_method<Rcvr, Method>::value, can_connect_method<Method, RealDst>::value>, useif<based_on<Rcvr, Connector>::value>> void connect(Rcvr & receiver, Method method, RealDst & dest) { connect(receiver, make_function(receiver, method), dest); } } //--------------------------------------------------------------------------- #endif
36.934363
260
0.672695
541edce7d78c2d8bb5d8716ea1e1ed4f68146ac8
189,403
h
C
Engine/Source/Runtime/RHI/Public/RHICommandList.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Runtime/RHI/Public/RHICommandList.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Runtime/RHI/Public/RHICommandList.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. /*============================================================================= RHICommandList.h: RHI Command List definitions for queueing up & executing later. =============================================================================*/ #pragma once #include "CoreTypes.h" #include "Misc/AssertionMacros.h" #include "HAL/UnrealMemory.h" #include "Templates/UnrealTemplate.h" #include "Math/Color.h" #include "Math/IntPoint.h" #include "Math/IntRect.h" #include "Math/Box2D.h" #include "Math/PerspectiveMatrix.h" #include "Math/TranslationMatrix.h" #include "Math/ScaleMatrix.h" #include "Math/Float16Color.h" #include "HAL/ThreadSafeCounter.h" #include "GenericPlatform/GenericPlatformProcess.h" #include "Misc/MemStack.h" #include "Misc/App.h" #include "Stats/Stats.h" #include "HAL/IConsoleManager.h" #include "Async/TaskGraphInterfaces.h" #include "HAL/LowLevelMemTracker.h" class FApp; class FBlendStateInitializerRHI; class FGraphicsPipelineStateInitializer; class FLastRenderTimeContainer; class FReadSurfaceDataFlags; class FRHICommandListBase; class FRHIComputeShader; class FRHIDepthRenderTargetView; class FRHIRenderTargetView; class FRHISetRenderTargetsInfo; class IRHICommandContext; class IRHIComputeContext; struct FBoundShaderStateInput; struct FDepthStencilStateInitializerRHI; struct FRasterizerStateInitializerRHI; struct FResolveParams; struct FRHIResourceCreateInfo; struct FRHIResourceInfo; struct FRHIUniformBufferLayout; struct FSamplerStateInitializerRHI; struct FTextureMemoryStats; class FRHIRenderPassCommandList; class FRHIParallelRenderPassCommandList; class FRHIRenderSubPassCommandList; enum class EAsyncComputeBudget; enum class EClearDepthStencil; enum class EResourceTransitionAccess; enum class EResourceTransitionPipeline; class FComputePipelineState; class FGraphicsPipelineState; // NVCHANGE_BEGIN: Nvidia Volumetric Lighting #if WITH_NVVOLUMETRICLIGHTING #include "NVVolumetricLightingRHI.h" #endif // NVCHANGE_END: Nvidia Volumetric Lighting DECLARE_STATS_GROUP(TEXT("RHICmdList"), STATGROUP_RHICMDLIST, STATCAT_Advanced); // set this one to get a stat for each RHI command #define RHI_STATS 0 #if RHI_STATS DECLARE_STATS_GROUP(TEXT("RHICommands"),STATGROUP_RHI_COMMANDS, STATCAT_Advanced); #define RHISTAT(Method) DECLARE_SCOPE_CYCLE_COUNTER(TEXT(#Method), STAT_RHI##Method, STATGROUP_RHI_COMMANDS) #else #define RHISTAT(Method) #endif extern RHI_API bool GUseRHIThread_InternalUseOnly; extern RHI_API bool GUseRHITaskThreads_InternalUseOnly; extern RHI_API bool GIsRunningRHIInSeparateThread_InternalUseOnly; extern RHI_API bool GIsRunningRHIInDedicatedThread_InternalUseOnly; extern RHI_API bool GIsRunningRHIInTaskThread_InternalUseOnly; /** * Whether the RHI commands are being run in a thread other than the render thread */ bool FORCEINLINE IsRunningRHIInSeparateThread() { return GIsRunningRHIInSeparateThread_InternalUseOnly; } /** * Whether the RHI commands are being run on a dedicated thread other than the render thread */ bool FORCEINLINE IsRunningRHIInDedicatedThread() { return GIsRunningRHIInDedicatedThread_InternalUseOnly; } /** * Whether the RHI commands are being run on a dedicated thread other than the render thread */ bool FORCEINLINE IsRunningRHIInTaskThread() { return GIsRunningRHIInTaskThread_InternalUseOnly; } extern RHI_API bool GEnableAsyncCompute; extern RHI_API TAutoConsoleVariable<int32> CVarRHICmdWidth; extern RHI_API TAutoConsoleVariable<int32> CVarRHICmdFlushRenderThreadTasks; class FRHICommandListBase; enum class ECmdList { EGfx, ECompute, }; class IRHICommandContextContainer { public: virtual ~IRHICommandContextContainer() { } virtual IRHICommandContext* GetContext() { return nullptr; } virtual void FinishContext() { check(0); } virtual void SubmitAndFreeContextContainer(int32 Index, int32 Num) { check(0); } }; struct FRHICommandBase { FRHICommandBase* Next; void(*ExecuteAndDestructPtr)(FRHICommandListBase& CmdList, FRHICommandBase *Cmd); FORCEINLINE FRHICommandBase(void(*InExecuteAndDestructPtr)(FRHICommandListBase& CmdList, FRHICommandBase *Cmd)) : Next(nullptr) , ExecuteAndDestructPtr(InExecuteAndDestructPtr) { } FORCEINLINE void CallExecuteAndDestruct(FRHICommandListBase& CmdList) { ExecuteAndDestructPtr(CmdList, this); } }; // Thread-safe allocator for GPU fences used in deferred command list execution // Fences are stored in a ringbuffer class RHI_API FRHICommandListFenceAllocator { public: static const int MAX_FENCE_INDICES = 4096; FRHICommandListFenceAllocator() { CurrentFenceIndex = 0; for ( int i=0; i<MAX_FENCE_INDICES; i++) { FenceIDs[i] = 0xffffffffffffffffull; FenceFrameNumber[i] = 0xffffffff; } } uint32 AllocFenceIndex() { check(IsInRenderingThread()); uint32 FenceIndex = ( FPlatformAtomics::InterlockedIncrement(&CurrentFenceIndex)-1 ) % MAX_FENCE_INDICES; check(FenceFrameNumber[FenceIndex] != GFrameNumberRenderThread); FenceFrameNumber[FenceIndex] = GFrameNumberRenderThread; return FenceIndex; } volatile uint64& GetFenceID( int32 FenceIndex ) { check( FenceIndex < MAX_FENCE_INDICES ); return FenceIDs[ FenceIndex ]; } private: volatile int32 CurrentFenceIndex; uint64 FenceIDs[MAX_FENCE_INDICES]; uint32 FenceFrameNumber[MAX_FENCE_INDICES]; }; extern RHI_API FRHICommandListFenceAllocator GRHIFenceAllocator; class RHI_API FRHICommandListBase : public FNoncopyable { public: FRHICommandListBase(); ~FRHICommandListBase(); /** Custom new/delete with recycling */ void* operator new(size_t Size); void operator delete(void *RawMemory); inline void Flush(); inline bool IsImmediate(); inline bool IsImmediateAsyncCompute(); const int32 GetUsedMemory() const; void QueueAsyncCommandListSubmit(FGraphEventRef& AnyThreadCompletionEvent, class FRHICommandList* CmdList); void QueueAsyncCommandListSubmit(FGraphEventRef& AnyThreadCompletionEvent, class FRHIRenderSubPassCommandList* CmdList); void QueueParallelAsyncCommandListSubmit(FGraphEventRef* AnyThreadCompletionEvents, bool bIsPrepass, class FRHICommandList** CmdLists, int32* NumDrawsIfKnown, int32 Num, int32 MinDrawsPerTranslate, bool bSpewMerge); void QueueParallelAsyncCommandListSubmit(FGraphEventRef* AnyThreadCompletionEvents, bool bIsPrepass, class FRHIRenderSubPassCommandList** CmdLists, int32* NumDrawsIfKnown, int32 Num, int32 MinDrawsPerTranslate, bool bSpewMerge); void QueueRenderThreadCommandListSubmit(FGraphEventRef& RenderThreadCompletionEvent, class FRHICommandList* CmdList); void QueueAsyncPipelineStateCompile(FGraphEventRef& AsyncCompileCompletionEvent); void QueueCommandListSubmit(class FRHICommandList* CmdList); void WaitForTasks(bool bKnownToBeComplete = false); void WaitForDispatch(); void WaitForRHIThreadTasks(); void HandleRTThreadTaskCompletion(const FGraphEventRef& MyCompletionGraphEvent); FORCEINLINE_DEBUGGABLE void* Alloc(int32 AllocSize, int32 Alignment) { return MemManager.Alloc(AllocSize, Alignment); } template <typename T> FORCEINLINE_DEBUGGABLE void* Alloc() { return Alloc(sizeof(T), alignof(T)); } FORCEINLINE_DEBUGGABLE TCHAR* AllocString(const TCHAR* Name) { int32 Len = FCString::Strlen(Name) + 1; TCHAR* NameCopy = (TCHAR*)Alloc(Len * (int32)sizeof(TCHAR), (int32)sizeof(TCHAR)); FCString::Strcpy(NameCopy, Len, Name); return NameCopy; } template <typename TCmd> FORCEINLINE_DEBUGGABLE void* AllocCommand() { checkSlow(!IsExecuting()); TCmd* Result = (TCmd*)Alloc<TCmd>(); ++NumCommands; *CommandLink = Result; CommandLink = &Result->Next; return Result; } FORCEINLINE uint32 GetUID() { return UID; } FORCEINLINE bool HasCommands() const { return (NumCommands > 0); } FORCEINLINE bool IsExecuting() const { return bExecuting; } bool Bypass(); FORCEINLINE void ExchangeCmdList(FRHICommandListBase& Other) { check(!RTTasks.Num() && !Other.RTTasks.Num()); FMemory::Memswap(this, &Other, sizeof(FRHICommandListBase)); if (CommandLink == &Other.Root) { CommandLink = &Root; } if (Other.CommandLink == &Root) { Other.CommandLink = &Other.Root; } } void SetContext(IRHICommandContext* InContext) { check(InContext); Context = InContext; } FORCEINLINE IRHICommandContext& GetContext() { checkSlow(Context); return *Context; } void SetComputeContext(IRHIComputeContext* InContext) { check(InContext); ComputeContext = InContext; } IRHIComputeContext& GetComputeContext() { checkSlow(ComputeContext); return *ComputeContext; } void CopyContext(FRHICommandListBase& ParentCommandList) { Context = ParentCommandList.Context; ComputeContext = ParentCommandList.ComputeContext; } struct FDrawUpData { uint32 PrimitiveType; uint32 NumPrimitives; uint32 NumVertices; uint32 VertexDataStride; void* OutVertexData; uint32 MinVertexIndex; uint32 NumIndices; uint32 IndexDataStride; void* OutIndexData; FDrawUpData() : PrimitiveType(PT_Num) , OutVertexData(nullptr) , OutIndexData(nullptr) { } }; private: FRHICommandBase* Root; FRHICommandBase** CommandLink; bool bExecuting; uint32 NumCommands; uint32 UID; IRHICommandContext* Context; IRHIComputeContext* ComputeContext; FMemStackBase MemManager; FGraphEventArray RTTasks; void Reset(); friend class FRHICommandListExecutor; friend class FRHICommandListIterator; public: TStatId ExecuteStat; enum class ERenderThreadContext { SceneRenderTargets, Num }; void *RenderThreadContexts[(int32)ERenderThreadContext::Num]; protected: //the values of this struct must be copied when the commandlist is split struct FPSOContext { uint32 CachedNumSimultanousRenderTargets = 0; TStaticArray<FRHIRenderTargetView, MaxSimultaneousRenderTargets> CachedRenderTargets; FRHIDepthRenderTargetView CachedDepthStencilTarget; } PSOContext; void CacheActiveRenderTargets( uint32 NewNumSimultaneousRenderTargets, const FRHIRenderTargetView* NewRenderTargetsRHI, const FRHIDepthRenderTargetView* NewDepthStencilTargetRHI ) { PSOContext.CachedNumSimultanousRenderTargets = NewNumSimultaneousRenderTargets; for (uint32 RTIdx = 0; RTIdx < PSOContext.CachedNumSimultanousRenderTargets; ++RTIdx) { PSOContext.CachedRenderTargets[RTIdx] = NewRenderTargetsRHI[RTIdx]; } PSOContext.CachedDepthStencilTarget = (NewDepthStencilTargetRHI) ? *NewDepthStencilTargetRHI : FRHIDepthRenderTargetView(); } void CacheActiveRenderTargets(const FRHIRenderPassInfo& Info) { FRHISetRenderTargetsInfo RTInfo; Info.ConvertToRenderTargetsInfo(RTInfo); CacheActiveRenderTargets(RTInfo.NumColorRenderTargets, RTInfo.ColorRenderTarget, &RTInfo.DepthStencilRenderTarget); } public: void CopyRenderThreadContexts(const FRHICommandListBase& ParentCommandList) { for (int32 Index = 0; ERenderThreadContext(Index) < ERenderThreadContext::Num; Index++) { RenderThreadContexts[Index] = ParentCommandList.RenderThreadContexts[Index]; } } void SetRenderThreadContext(void* InContext, ERenderThreadContext Slot) { RenderThreadContexts[int32(Slot)] = InContext; } FORCEINLINE void* GetRenderThreadContext(ERenderThreadContext Slot) { return RenderThreadContexts[int32(Slot)]; } FDrawUpData DrawUPData; struct FCommonData { class FRHICommandListBase* Parent = nullptr; struct FLocalCmdListRenderPass* LocalRHIRenderPass = nullptr; struct FLocalCmdListParallelRenderPass* LocalRHIParallelRenderPass = nullptr; struct FLocalCmdListRenderSubPass* LocalRHIRenderSubPass = nullptr; enum class ECmdListType { Immediate = 1, RenderSubPass, Regular, }; ECmdListType Type = ECmdListType::Regular; }; FCommonData Data; }; template<typename TCmd> struct FRHICommand : public FRHICommandBase { FORCEINLINE FRHICommand() : FRHICommandBase(&ExecuteAndDestruct) { } static FORCEINLINE void ExecuteAndDestruct(FRHICommandListBase& CmdList, FRHICommandBase *Cmd) { TCmd *ThisCmd = (TCmd*)Cmd; ThisCmd->Execute(CmdList); ThisCmd->~TCmd(); } }; struct FRHICommandBeginUpdateMultiFrameResource : public FRHICommand<FRHICommandBeginUpdateMultiFrameResource> { FTextureRHIParamRef Texture; FORCEINLINE_DEBUGGABLE FRHICommandBeginUpdateMultiFrameResource(FTextureRHIParamRef InTexture) : Texture(InTexture) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandEndUpdateMultiFrameResource : public FRHICommand<FRHICommandEndUpdateMultiFrameResource> { FTextureRHIParamRef Texture; FORCEINLINE_DEBUGGABLE FRHICommandEndUpdateMultiFrameResource(FTextureRHIParamRef InTexture) : Texture(InTexture) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandBeginUpdateMultiFrameUAV : public FRHICommand<FRHICommandBeginUpdateMultiFrameResource> { FUnorderedAccessViewRHIParamRef UAV; FORCEINLINE_DEBUGGABLE FRHICommandBeginUpdateMultiFrameUAV(FUnorderedAccessViewRHIParamRef InUAV) : UAV(InUAV) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandEndUpdateMultiFrameUAV : public FRHICommand<FRHICommandEndUpdateMultiFrameResource> { FUnorderedAccessViewRHIParamRef UAV; FORCEINLINE_DEBUGGABLE FRHICommandEndUpdateMultiFrameUAV(FUnorderedAccessViewRHIParamRef InUAV) : UAV(InUAV) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandSetRasterizerState : public FRHICommand<FRHICommandSetRasterizerState> { FRasterizerStateRHIParamRef State; FORCEINLINE_DEBUGGABLE FRHICommandSetRasterizerState(FRasterizerStateRHIParamRef InState) : State(InState) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandSetDepthStencilState : public FRHICommand<FRHICommandSetDepthStencilState> { FDepthStencilStateRHIParamRef State; uint32 StencilRef; FORCEINLINE_DEBUGGABLE FRHICommandSetDepthStencilState(FDepthStencilStateRHIParamRef InState, uint32 InStencilRef) : State(InState) , StencilRef(InStencilRef) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandSetStencilRef : public FRHICommand<FRHICommandSetStencilRef> { uint32 StencilRef; FORCEINLINE_DEBUGGABLE FRHICommandSetStencilRef(uint32 InStencilRef) : StencilRef(InStencilRef) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; template <typename TShaderRHIParamRef, ECmdList CmdListType> struct FRHICommandSetShaderParameter : public FRHICommand<FRHICommandSetShaderParameter<TShaderRHIParamRef, CmdListType> > { TShaderRHIParamRef Shader; const void* NewValue; uint32 BufferIndex; uint32 BaseIndex; uint32 NumBytes; FORCEINLINE_DEBUGGABLE FRHICommandSetShaderParameter(TShaderRHIParamRef InShader, uint32 InBufferIndex, uint32 InBaseIndex, uint32 InNumBytes, const void* InNewValue) : Shader(InShader) , NewValue(InNewValue) , BufferIndex(InBufferIndex) , BaseIndex(InBaseIndex) , NumBytes(InNumBytes) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; template <typename TShaderRHIParamRef, ECmdList CmdListType> struct FRHICommandSetShaderUniformBuffer : public FRHICommand<FRHICommandSetShaderUniformBuffer<TShaderRHIParamRef, CmdListType> > { TShaderRHIParamRef Shader; uint32 BaseIndex; FUniformBufferRHIParamRef UniformBuffer; FORCEINLINE_DEBUGGABLE FRHICommandSetShaderUniformBuffer(TShaderRHIParamRef InShader, uint32 InBaseIndex, FUniformBufferRHIParamRef InUniformBuffer) : Shader(InShader) , BaseIndex(InBaseIndex) , UniformBuffer(InUniformBuffer) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; template <typename TShaderRHIParamRef, ECmdList CmdListType> struct FRHICommandSetShaderTexture : public FRHICommand<FRHICommandSetShaderTexture<TShaderRHIParamRef, CmdListType> > { TShaderRHIParamRef Shader; uint32 TextureIndex; FTextureRHIParamRef Texture; FORCEINLINE_DEBUGGABLE FRHICommandSetShaderTexture(TShaderRHIParamRef InShader, uint32 InTextureIndex, FTextureRHIParamRef InTexture) : Shader(InShader) , TextureIndex(InTextureIndex) , Texture(InTexture) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; template <typename TShaderRHIParamRef, ECmdList CmdListType> struct FRHICommandSetShaderResourceViewParameter : public FRHICommand<FRHICommandSetShaderResourceViewParameter<TShaderRHIParamRef, CmdListType> > { TShaderRHIParamRef Shader; uint32 SamplerIndex; FShaderResourceViewRHIParamRef SRV; FORCEINLINE_DEBUGGABLE FRHICommandSetShaderResourceViewParameter(TShaderRHIParamRef InShader, uint32 InSamplerIndex, FShaderResourceViewRHIParamRef InSRV) : Shader(InShader) , SamplerIndex(InSamplerIndex) , SRV(InSRV) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; template <typename TShaderRHIParamRef, ECmdList CmdListType> struct FRHICommandSetUAVParameter : public FRHICommand<FRHICommandSetUAVParameter<TShaderRHIParamRef, CmdListType> > { TShaderRHIParamRef Shader; uint32 UAVIndex; FUnorderedAccessViewRHIParamRef UAV; FORCEINLINE_DEBUGGABLE FRHICommandSetUAVParameter(TShaderRHIParamRef InShader, uint32 InUAVIndex, FUnorderedAccessViewRHIParamRef InUAV) : Shader(InShader) , UAVIndex(InUAVIndex) , UAV(InUAV) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; template <typename TShaderRHIParamRef, ECmdList CmdListType> struct FRHICommandSetUAVParameter_IntialCount : public FRHICommand<FRHICommandSetUAVParameter_IntialCount<TShaderRHIParamRef, CmdListType> > { TShaderRHIParamRef Shader; uint32 UAVIndex; FUnorderedAccessViewRHIParamRef UAV; uint32 InitialCount; FORCEINLINE_DEBUGGABLE FRHICommandSetUAVParameter_IntialCount(TShaderRHIParamRef InShader, uint32 InUAVIndex, FUnorderedAccessViewRHIParamRef InUAV, uint32 InInitialCount) : Shader(InShader) , UAVIndex(InUAVIndex) , UAV(InUAV) , InitialCount(InInitialCount) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; template <typename TShaderRHIParamRef, ECmdList CmdListType> struct FRHICommandSetShaderSampler : public FRHICommand<FRHICommandSetShaderSampler<TShaderRHIParamRef, CmdListType> > { TShaderRHIParamRef Shader; uint32 SamplerIndex; FSamplerStateRHIParamRef Sampler; FORCEINLINE_DEBUGGABLE FRHICommandSetShaderSampler(TShaderRHIParamRef InShader, uint32 InSamplerIndex, FSamplerStateRHIParamRef InSampler) : Shader(InShader) , SamplerIndex(InSamplerIndex) , Sampler(InSampler) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; // WaveWorks Start struct FRHICommandSetWaveWorksState : public FRHICommand < FRHICommandSetWaveWorksState > { FWaveWorksRHIParamRef State; FMatrix ViewMatrix; TArray<uint32> ShaderInputMappings; FORCEINLINE_DEBUGGABLE FRHICommandSetWaveWorksState(FWaveWorksRHIParamRef InState, const FMatrix& InViewMatrix, const TArray<uint32>& InShaderInputMappings) : State(InState) , ViewMatrix(InViewMatrix) , ShaderInputMappings(InShaderInputMappings) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; // WaveWorks End struct FRHICommandDrawPrimitive : public FRHICommand<FRHICommandDrawPrimitive> { uint32 PrimitiveType; uint32 BaseVertexIndex; uint32 NumPrimitives; uint32 NumInstances; FORCEINLINE_DEBUGGABLE FRHICommandDrawPrimitive(uint32 InPrimitiveType, uint32 InBaseVertexIndex, uint32 InNumPrimitives, uint32 InNumInstances) : PrimitiveType(InPrimitiveType) , BaseVertexIndex(InBaseVertexIndex) , NumPrimitives(InNumPrimitives) , NumInstances(InNumInstances) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandDrawIndexedPrimitive : public FRHICommand<FRHICommandDrawIndexedPrimitive> { FIndexBufferRHIParamRef IndexBuffer; uint32 PrimitiveType; int32 BaseVertexIndex; uint32 FirstInstance; uint32 NumVertices; uint32 StartIndex; uint32 NumPrimitives; uint32 NumInstances; FORCEINLINE_DEBUGGABLE FRHICommandDrawIndexedPrimitive(FIndexBufferRHIParamRef InIndexBuffer, uint32 InPrimitiveType, int32 InBaseVertexIndex, uint32 InFirstInstance, uint32 InNumVertices, uint32 InStartIndex, uint32 InNumPrimitives, uint32 InNumInstances) : IndexBuffer(InIndexBuffer) , PrimitiveType(InPrimitiveType) , BaseVertexIndex(InBaseVertexIndex) , FirstInstance(InFirstInstance) , NumVertices(InNumVertices) , StartIndex(InStartIndex) , NumPrimitives(InNumPrimitives) , NumInstances(InNumInstances) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandSetBoundShaderState : public FRHICommand<FRHICommandSetBoundShaderState> { FBoundShaderStateRHIParamRef BoundShaderState; FORCEINLINE_DEBUGGABLE FRHICommandSetBoundShaderState(FBoundShaderStateRHIParamRef InBoundShaderState) : BoundShaderState(InBoundShaderState) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandSetBlendState : public FRHICommand<FRHICommandSetBlendState> { FBlendStateRHIParamRef State; FLinearColor BlendFactor; FORCEINLINE_DEBUGGABLE FRHICommandSetBlendState(FBlendStateRHIParamRef InState, const FLinearColor& InBlendFactor) : State(InState) , BlendFactor(InBlendFactor) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandSetBlendFactor : public FRHICommand<FRHICommandSetBlendFactor> { FLinearColor BlendFactor; FORCEINLINE_DEBUGGABLE FRHICommandSetBlendFactor(const FLinearColor& InBlendFactor) : BlendFactor(InBlendFactor) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandSetStreamSourceDEPRECATED : public FRHICommand<FRHICommandSetStreamSourceDEPRECATED> { uint32 StreamIndex; FVertexBufferRHIParamRef VertexBuffer; uint32 Stride; uint32 Offset; FORCEINLINE_DEBUGGABLE FRHICommandSetStreamSourceDEPRECATED(uint32 InStreamIndex, FVertexBufferRHIParamRef InVertexBuffer, uint32 InStride, uint32 InOffset) : StreamIndex(InStreamIndex) , VertexBuffer(InVertexBuffer) , Stride(InStride) , Offset(InOffset) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandSetStreamSource : public FRHICommand<FRHICommandSetStreamSource> { uint32 StreamIndex; FVertexBufferRHIParamRef VertexBuffer; uint32 Offset; FORCEINLINE_DEBUGGABLE FRHICommandSetStreamSource(uint32 InStreamIndex, FVertexBufferRHIParamRef InVertexBuffer, uint32 InOffset) : StreamIndex(InStreamIndex) , VertexBuffer(InVertexBuffer) , Offset(InOffset) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandSetViewport : public FRHICommand<FRHICommandSetViewport> { uint32 MinX; uint32 MinY; float MinZ; uint32 MaxX; uint32 MaxY; float MaxZ; FORCEINLINE_DEBUGGABLE FRHICommandSetViewport(uint32 InMinX, uint32 InMinY, float InMinZ, uint32 InMaxX, uint32 InMaxY, float InMaxZ) : MinX(InMinX) , MinY(InMinY) , MinZ(InMinZ) , MaxX(InMaxX) , MaxY(InMaxY) , MaxZ(InMaxZ) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandSetStereoViewport : public FRHICommand<FRHICommandSetStereoViewport> { uint32 LeftMinX; uint32 RightMinX; uint32 LeftMinY; uint32 RightMinY; float MinZ; uint32 LeftMaxX; uint32 RightMaxX; uint32 LeftMaxY; uint32 RightMaxY; float MaxZ; FORCEINLINE_DEBUGGABLE FRHICommandSetStereoViewport(uint32 InLeftMinX, uint32 InRightMinX, uint32 InLeftMinY, uint32 InRightMinY, float InMinZ, uint32 InLeftMaxX, uint32 InRightMaxX, uint32 InLeftMaxY, uint32 InRightMaxY, float InMaxZ) : LeftMinX(InLeftMinX) , RightMinX(InRightMinX) , LeftMinY(InLeftMinY) , RightMinY(InRightMinY) , MinZ(InMinZ) , LeftMaxX(InLeftMaxX) , RightMaxX(InRightMaxX) , LeftMaxY(InLeftMaxY) , RightMaxY(InRightMaxY) , MaxZ(InMaxZ) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandSetScissorRect : public FRHICommand<FRHICommandSetScissorRect> { bool bEnable; uint32 MinX; uint32 MinY; uint32 MaxX; uint32 MaxY; FORCEINLINE_DEBUGGABLE FRHICommandSetScissorRect(bool InbEnable, uint32 InMinX, uint32 InMinY, uint32 InMaxX, uint32 InMaxY) : bEnable(InbEnable) , MinX(InMinX) , MinY(InMinY) , MaxX(InMaxX) , MaxY(InMaxY) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandSetRenderTargets : public FRHICommand<FRHICommandSetRenderTargets> { uint32 NewNumSimultaneousRenderTargets; FRHIRenderTargetView NewRenderTargetsRHI[MaxSimultaneousRenderTargets]; FRHIDepthRenderTargetView NewDepthStencilTarget; uint32 NewNumUAVs; FUnorderedAccessViewRHIParamRef UAVs[MaxSimultaneousUAVs]; FORCEINLINE_DEBUGGABLE FRHICommandSetRenderTargets( uint32 InNewNumSimultaneousRenderTargets, const FRHIRenderTargetView* InNewRenderTargetsRHI, const FRHIDepthRenderTargetView* InNewDepthStencilTargetRHI, uint32 InNewNumUAVs, const FUnorderedAccessViewRHIParamRef* InUAVs ) : NewNumSimultaneousRenderTargets(InNewNumSimultaneousRenderTargets) , NewNumUAVs(InNewNumUAVs) { check(InNewNumSimultaneousRenderTargets <= MaxSimultaneousRenderTargets && InNewNumUAVs <= MaxSimultaneousUAVs); for (uint32 Index = 0; Index < NewNumSimultaneousRenderTargets; Index++) { NewRenderTargetsRHI[Index] = InNewRenderTargetsRHI[Index]; } for (uint32 Index = 0; Index < NewNumUAVs; Index++) { UAVs[Index] = InUAVs[Index]; } if (InNewDepthStencilTargetRHI) { NewDepthStencilTarget = *InNewDepthStencilTargetRHI; } } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FLocalCmdListRenderPass { TRefCountPtr<FRHIRenderPass> RenderPass; //~FLocalCmdListRenderPass() //{ // FPlatformMisc::LowLevelOutputDebugStringf(TEXT("~FLocalCmdListRenderPass %p, RP %p\n"), this, RenderPass.GetReference()); //} }; struct FRHICommandBeginRenderPass : public FRHICommand<FRHICommandBeginRenderPass> { FRHIRenderPassInfo Info; FLocalCmdListRenderPass* LocalRenderPass; const TCHAR* Name; FRHICommandBeginRenderPass(const FRHIRenderPassInfo& InInfo, FLocalCmdListRenderPass* InLocalRenderPass, const TCHAR* InName) : Info(InInfo) , LocalRenderPass(InLocalRenderPass) , Name(InName) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandEndRenderPass : public FRHICommand<FRHICommandEndRenderPass> { FLocalCmdListRenderPass* LocalRenderPass; FRHICommandEndRenderPass(FLocalCmdListRenderPass* InLocalRenderPass) : LocalRenderPass(InLocalRenderPass) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FLocalCmdListParallelRenderPass { TRefCountPtr<FRHIParallelRenderPass> RenderPass; }; struct FRHICommandBeginParallelRenderPass : public FRHICommand<FRHICommandBeginParallelRenderPass> { FRHIRenderPassInfo Info; FLocalCmdListParallelRenderPass* LocalRenderPass; const TCHAR* Name; FRHICommandBeginParallelRenderPass(const FRHIRenderPassInfo& InInfo, FLocalCmdListParallelRenderPass* InLocalRenderPass, const TCHAR* InName) : Info(InInfo) , LocalRenderPass(InLocalRenderPass) , Name(InName) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandEndParallelRenderPass : public FRHICommand<FRHICommandEndParallelRenderPass> { FLocalCmdListParallelRenderPass* LocalRenderPass; FRHICommandEndParallelRenderPass(FLocalCmdListParallelRenderPass* InLocalRenderPass) : LocalRenderPass(InLocalRenderPass) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FLocalCmdListRenderSubPass { TRefCountPtr<FRHIRenderSubPass> RenderSubPass; }; struct FRHICommandBeginRenderSubPass : public FRHICommand<FRHICommandBeginRenderSubPass> { FLocalCmdListParallelRenderPass* LocalRenderPass; FLocalCmdListRenderSubPass* LocalRenderSubPass; FRHICommandBeginRenderSubPass(FLocalCmdListParallelRenderPass* InLocalRenderPass, FLocalCmdListRenderSubPass* InLocalRenderSubPass) : LocalRenderPass(InLocalRenderPass) , LocalRenderSubPass(InLocalRenderSubPass) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandEndRenderSubPass : public FRHICommand<FRHICommandEndRenderSubPass> { FLocalCmdListParallelRenderPass* LocalRenderPass; FLocalCmdListRenderSubPass* LocalRenderSubPass; FRHICommandEndRenderSubPass(FLocalCmdListParallelRenderPass* InLocalRenderPass, FLocalCmdListRenderSubPass* InLocalRenderSubPass) : LocalRenderPass(InLocalRenderPass) , LocalRenderSubPass(InLocalRenderSubPass) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandSetRenderTargetsAndClear : public FRHICommand<FRHICommandSetRenderTargetsAndClear> { FRHISetRenderTargetsInfo RenderTargetsInfo; FORCEINLINE_DEBUGGABLE FRHICommandSetRenderTargetsAndClear(const FRHISetRenderTargetsInfo& InRenderTargetsInfo) : RenderTargetsInfo(InRenderTargetsInfo) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandBindClearMRTValues : public FRHICommand<FRHICommandBindClearMRTValues> { bool bClearColor; bool bClearDepth; bool bClearStencil; FORCEINLINE_DEBUGGABLE FRHICommandBindClearMRTValues( bool InbClearColor, bool InbClearDepth, bool InbClearStencil ) : bClearColor(InbClearColor) , bClearDepth(InbClearDepth) , bClearStencil(InbClearStencil) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandEndDrawPrimitiveUP : public FRHICommand<FRHICommandEndDrawPrimitiveUP> { uint32 PrimitiveType; uint32 NumPrimitives; uint32 NumVertices; uint32 VertexDataStride; void* OutVertexData; FORCEINLINE_DEBUGGABLE FRHICommandEndDrawPrimitiveUP(uint32 InPrimitiveType, uint32 InNumPrimitives, uint32 InNumVertices, uint32 InVertexDataStride, void* InOutVertexData) : PrimitiveType(InPrimitiveType) , NumPrimitives(InNumPrimitives) , NumVertices(InNumVertices) , VertexDataStride(InVertexDataStride) , OutVertexData(InOutVertexData) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandEndDrawIndexedPrimitiveUP : public FRHICommand<FRHICommandEndDrawIndexedPrimitiveUP> { uint32 PrimitiveType; uint32 NumPrimitives; uint32 NumVertices; uint32 VertexDataStride; void* OutVertexData; uint32 MinVertexIndex; uint32 NumIndices; uint32 IndexDataStride; void* OutIndexData; FORCEINLINE_DEBUGGABLE FRHICommandEndDrawIndexedPrimitiveUP(uint32 InPrimitiveType, uint32 InNumPrimitives, uint32 InNumVertices, uint32 InVertexDataStride, void* InOutVertexData, uint32 InMinVertexIndex, uint32 InNumIndices, uint32 InIndexDataStride, void* InOutIndexData) : PrimitiveType(InPrimitiveType) , NumPrimitives(InNumPrimitives) , NumVertices(InNumVertices) , VertexDataStride(InVertexDataStride) , OutVertexData(InOutVertexData) , MinVertexIndex(InMinVertexIndex) , NumIndices(InNumIndices) , IndexDataStride(InIndexDataStride) , OutIndexData(InOutIndexData) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; template<ECmdList CmdListType> struct FRHICommandSetComputeShader : public FRHICommand<FRHICommandSetComputeShader<CmdListType>> { FComputeShaderRHIParamRef ComputeShader; FORCEINLINE_DEBUGGABLE FRHICommandSetComputeShader(FComputeShaderRHIParamRef InComputeShader) : ComputeShader(InComputeShader) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; template<ECmdList CmdListType> struct FRHICommandSetComputePipelineState : public FRHICommand<FRHICommandSetComputePipelineState<CmdListType>> { FComputePipelineState* ComputePipelineState; FORCEINLINE_DEBUGGABLE FRHICommandSetComputePipelineState(FComputePipelineState* InComputePipelineState) : ComputePipelineState(InComputePipelineState) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandSetGraphicsPipelineState : public FRHICommand<FRHICommandSetGraphicsPipelineState> { FGraphicsPipelineState* GraphicsPipelineState; FORCEINLINE_DEBUGGABLE FRHICommandSetGraphicsPipelineState(FGraphicsPipelineState* InGraphicsPipelineState) : GraphicsPipelineState(InGraphicsPipelineState) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; template<ECmdList CmdListType> struct FRHICommandDispatchComputeShader : public FRHICommand<FRHICommandDispatchComputeShader<CmdListType>> { uint32 ThreadGroupCountX; uint32 ThreadGroupCountY; uint32 ThreadGroupCountZ; FORCEINLINE_DEBUGGABLE FRHICommandDispatchComputeShader(uint32 InThreadGroupCountX, uint32 InThreadGroupCountY, uint32 InThreadGroupCountZ) : ThreadGroupCountX(InThreadGroupCountX) , ThreadGroupCountY(InThreadGroupCountY) , ThreadGroupCountZ(InThreadGroupCountZ) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; template<ECmdList CmdListType> struct FRHICommandDispatchIndirectComputeShader : public FRHICommand<FRHICommandDispatchIndirectComputeShader<CmdListType>> { FVertexBufferRHIParamRef ArgumentBuffer; uint32 ArgumentOffset; FORCEINLINE_DEBUGGABLE FRHICommandDispatchIndirectComputeShader(FVertexBufferRHIParamRef InArgumentBuffer, uint32 InArgumentOffset) : ArgumentBuffer(InArgumentBuffer) , ArgumentOffset(InArgumentOffset) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandAutomaticCacheFlushAfterComputeShader : public FRHICommand<FRHICommandAutomaticCacheFlushAfterComputeShader> { bool bEnable; FORCEINLINE_DEBUGGABLE FRHICommandAutomaticCacheFlushAfterComputeShader(bool InbEnable) : bEnable(InbEnable) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandFlushComputeShaderCache : public FRHICommand<FRHICommandFlushComputeShaderCache> { RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandDrawPrimitiveIndirect : public FRHICommand<FRHICommandDrawPrimitiveIndirect> { FVertexBufferRHIParamRef ArgumentBuffer; uint32 PrimitiveType; uint32 ArgumentOffset; FORCEINLINE_DEBUGGABLE FRHICommandDrawPrimitiveIndirect(uint32 InPrimitiveType, FVertexBufferRHIParamRef InArgumentBuffer, uint32 InArgumentOffset) : ArgumentBuffer(InArgumentBuffer) , PrimitiveType(InPrimitiveType) , ArgumentOffset(InArgumentOffset) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandDrawIndexedIndirect : public FRHICommand<FRHICommandDrawIndexedIndirect> { FIndexBufferRHIParamRef IndexBufferRHI; uint32 PrimitiveType; FStructuredBufferRHIParamRef ArgumentsBufferRHI; uint32 DrawArgumentsIndex; uint32 NumInstances; FORCEINLINE_DEBUGGABLE FRHICommandDrawIndexedIndirect(FIndexBufferRHIParamRef InIndexBufferRHI, uint32 InPrimitiveType, FStructuredBufferRHIParamRef InArgumentsBufferRHI, uint32 InDrawArgumentsIndex, uint32 InNumInstances) : IndexBufferRHI(InIndexBufferRHI) , PrimitiveType(InPrimitiveType) , ArgumentsBufferRHI(InArgumentsBufferRHI) , DrawArgumentsIndex(InDrawArgumentsIndex) , NumInstances(InNumInstances) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandDrawIndexedPrimitiveIndirect : public FRHICommand<FRHICommandDrawIndexedPrimitiveIndirect> { FIndexBufferRHIParamRef IndexBuffer; FVertexBufferRHIParamRef ArgumentsBuffer; uint32 PrimitiveType; uint32 ArgumentOffset; FORCEINLINE_DEBUGGABLE FRHICommandDrawIndexedPrimitiveIndirect(uint32 InPrimitiveType, FIndexBufferRHIParamRef InIndexBuffer, FVertexBufferRHIParamRef InArgumentsBuffer, uint32 InArgumentOffset) : IndexBuffer(InIndexBuffer) , ArgumentsBuffer(InArgumentsBuffer) , PrimitiveType(InPrimitiveType) , ArgumentOffset(InArgumentOffset) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandEnableDepthBoundsTest : public FRHICommand<FRHICommandEnableDepthBoundsTest> { bool bEnable; float MinDepth; float MaxDepth; FORCEINLINE_DEBUGGABLE FRHICommandEnableDepthBoundsTest(bool InbEnable, float InMinDepth, float InMaxDepth) : bEnable(InbEnable) , MinDepth(InMinDepth) , MaxDepth(InMaxDepth) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandClearTinyUAV : public FRHICommand<FRHICommandClearTinyUAV> { FUnorderedAccessViewRHIParamRef UnorderedAccessViewRHI; uint32 Values[4]; FORCEINLINE_DEBUGGABLE FRHICommandClearTinyUAV(FUnorderedAccessViewRHIParamRef InUnorderedAccessViewRHI, const uint32* InValues) : UnorderedAccessViewRHI(InUnorderedAccessViewRHI) { Values[0] = InValues[0]; Values[1] = InValues[1]; Values[2] = InValues[2]; Values[3] = InValues[3]; } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandCopyToResolveTarget : public FRHICommand<FRHICommandCopyToResolveTarget> { FResolveParams ResolveParams; FTextureRHIParamRef SourceTexture; FTextureRHIParamRef DestTexture; bool bKeepOriginalSurface; FORCEINLINE_DEBUGGABLE FRHICommandCopyToResolveTarget(FTextureRHIParamRef InSourceTexture, FTextureRHIParamRef InDestTexture, bool InbKeepOriginalSurface, const FResolveParams& InResolveParams) : ResolveParams(InResolveParams) , SourceTexture(InSourceTexture) , DestTexture(InDestTexture) , bKeepOriginalSurface(InbKeepOriginalSurface) { ensure(SourceTexture); ensure(DestTexture); ensure(SourceTexture->GetTexture2D() || SourceTexture->GetTexture3D() || SourceTexture->GetTextureCube()); ensure(DestTexture->GetTexture2D() || DestTexture->GetTexture3D() || DestTexture->GetTextureCube()); } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandCopyTexture : public FRHICommand<FRHICommandCopyTexture> { FResolveParams ResolveParams; FTextureRHIParamRef SourceTexture; FTextureRHIParamRef DestTexture; FORCEINLINE_DEBUGGABLE FRHICommandCopyTexture(FTextureRHIParamRef InSourceTexture, FTextureRHIParamRef InDestTexture, const FResolveParams& InResolveParams) : ResolveParams(InResolveParams) , SourceTexture(InSourceTexture) , DestTexture(InDestTexture) { ensure(SourceTexture); ensure(DestTexture); ensure(SourceTexture->GetTexture2D() || SourceTexture->GetTexture3D() || SourceTexture->GetTextureCube()); ensure(DestTexture->GetTexture2D() || DestTexture->GetTexture3D() || DestTexture->GetTextureCube()); } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandTransitionTextures : public FRHICommand<FRHICommandTransitionTextures> { int32 NumTextures; FTextureRHIParamRef* Textures; // Pointer to an array of textures, allocated inline with the command list EResourceTransitionAccess TransitionType; FORCEINLINE_DEBUGGABLE FRHICommandTransitionTextures(EResourceTransitionAccess InTransitionType, FTextureRHIParamRef* InTextures, int32 InNumTextures) : NumTextures(InNumTextures) , Textures(InTextures) , TransitionType(InTransitionType) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandTransitionTexturesArray : public FRHICommand<FRHICommandTransitionTexturesArray> { TArray<FTextureRHIParamRef>& Textures; EResourceTransitionAccess TransitionType; FORCEINLINE_DEBUGGABLE FRHICommandTransitionTexturesArray(EResourceTransitionAccess InTransitionType, TArray<FTextureRHIParamRef>& InTextures) : Textures(InTextures) , TransitionType(InTransitionType) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; template<ECmdList CmdListType> struct FRHICommandTransitionUAVs : public FRHICommand<FRHICommandTransitionUAVs<CmdListType>> { int32 NumUAVs; FUnorderedAccessViewRHIParamRef* UAVs; // Pointer to an array of UAVs, allocated inline with the command list EResourceTransitionAccess TransitionType; EResourceTransitionPipeline TransitionPipeline; FComputeFenceRHIParamRef WriteFence; FORCEINLINE_DEBUGGABLE FRHICommandTransitionUAVs(EResourceTransitionAccess InTransitionType, EResourceTransitionPipeline InTransitionPipeline, FUnorderedAccessViewRHIParamRef* InUAVs, int32 InNumUAVs, FComputeFenceRHIParamRef InWriteFence) : NumUAVs(InNumUAVs) , UAVs(InUAVs) , TransitionType(InTransitionType) , TransitionPipeline(InTransitionPipeline) , WriteFence(InWriteFence) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; template<ECmdList CmdListType> struct FRHICommandSetAsyncComputeBudget : public FRHICommand<FRHICommandSetAsyncComputeBudget<CmdListType>> { EAsyncComputeBudget Budget; FORCEINLINE_DEBUGGABLE FRHICommandSetAsyncComputeBudget(EAsyncComputeBudget InBudget) : Budget(InBudget) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; template<ECmdList CmdListType> struct FRHICommandWaitComputeFence : public FRHICommand<FRHICommandWaitComputeFence<CmdListType>> { FComputeFenceRHIParamRef WaitFence; FORCEINLINE_DEBUGGABLE FRHICommandWaitComputeFence(FComputeFenceRHIParamRef InWaitFence) : WaitFence(InWaitFence) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandClearColorTexture : public FRHICommand<FRHICommandClearColorTexture> { FTextureRHIParamRef Texture; FLinearColor Color; FORCEINLINE_DEBUGGABLE FRHICommandClearColorTexture( FTextureRHIParamRef InTexture, const FLinearColor& InColor ) : Texture(InTexture) , Color(InColor) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandClearDepthStencilTexture : public FRHICommand<FRHICommandClearDepthStencilTexture> { FTextureRHIParamRef Texture; float Depth; uint32 Stencil; EClearDepthStencil ClearDepthStencil; FORCEINLINE_DEBUGGABLE FRHICommandClearDepthStencilTexture( FTextureRHIParamRef InTexture, EClearDepthStencil InClearDepthStencil, float InDepth, uint32 InStencil ) : Texture(InTexture) , Depth(InDepth) , Stencil(InStencil) , ClearDepthStencil(InClearDepthStencil) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandClearColorTextures : public FRHICommand<FRHICommandClearColorTextures> { FLinearColor ColorArray[MaxSimultaneousRenderTargets]; FTextureRHIParamRef Textures[MaxSimultaneousRenderTargets]; int32 NumClearColors; FORCEINLINE_DEBUGGABLE FRHICommandClearColorTextures( int32 InNumClearColors, FTextureRHIParamRef* InTextures, const FLinearColor* InColorArray ) : NumClearColors(InNumClearColors) { check(InNumClearColors <= MaxSimultaneousRenderTargets); for (int32 Index = 0; Index < InNumClearColors; Index++) { ColorArray[Index] = InColorArray[Index]; Textures[Index] = InTextures[Index]; } } RHI_API void Execute(FRHICommandListBase& CmdList); }; // WaveWorks Begin struct FQuadTreeWaveWorksArgsWorkArea { #if DO_CHECK // the below variables are used in check(), which can be enabled in Shipping builds (see Build.h) FRHICommandListBase* CheckCmdList; int32 UID; #endif FWaveWorksRHIRef WaveWorks; FMatrix ViewMatrix; FMatrix ProjMatrix; TArray<uint32> ShaderInputMappings; struct GFSDK_WaveWorks_Quadtree* QuadTreeHandle; FORCEINLINE_DEBUGGABLE FQuadTreeWaveWorksArgsWorkArea( FRHICommandListBase* InCheckCmdList, FWaveWorksRHIRef _WaveWorks, struct GFSDK_WaveWorks_Quadtree* _QuadTreeHandle, FMatrix _ViewMatrix, FMatrix _ProjMatrix, TArray<uint32> _ShaderInputMappings ) : WaveWorks(_WaveWorks) , QuadTreeHandle(_QuadTreeHandle) , ViewMatrix(_ViewMatrix) , ProjMatrix(_ProjMatrix) , ShaderInputMappings(_ShaderInputMappings) #if DO_CHECK , CheckCmdList(InCheckCmdList) , UID(InCheckCmdList->GetUID()) #endif { } }; // WaveWorks End // WaveWorks Begin struct FRHICommandBuildDrawQuadTreeWaveWorks : public FRHICommand<FRHICommandBuildDrawQuadTreeWaveWorks> { FQuadTreeWaveWorksArgsWorkArea WorkArea; FORCEINLINE_DEBUGGABLE FRHICommandBuildDrawQuadTreeWaveWorks( FRHICommandListBase* CheckCmdList, FWaveWorksRHIRef WaveWorks, struct GFSDK_WaveWorks_Quadtree* QuadTreeHandle, FMatrix ViewMatrix, FMatrix ProjMatrix, TArray<uint32> ShaderInputMappings ) : WorkArea(CheckCmdList, WaveWorks, QuadTreeHandle, ViewMatrix, ProjMatrix, ShaderInputMappings) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; // WaveWorks End struct FComputedGraphicsPipelineState { FGraphicsPipelineStateRHIRef GraphicsPipelineState; int32 UseCount; FComputedGraphicsPipelineState() : UseCount(0) { } }; struct FLocalGraphicsPipelineStateWorkArea { FGraphicsPipelineStateInitializer Args; FComputedGraphicsPipelineState* ComputedGraphicsPipelineState; #if DO_CHECK // the below variables are used in check(), which can be enabled in Shipping builds (see Build.h) FRHICommandListBase* CheckCmdList; int32 UID; #endif FORCEINLINE_DEBUGGABLE FLocalGraphicsPipelineStateWorkArea( FRHICommandListBase* InCheckCmdList, const FGraphicsPipelineStateInitializer& Initializer ) : Args(Initializer) #if DO_CHECK , CheckCmdList(InCheckCmdList) , UID(InCheckCmdList->GetUID()) #endif { ComputedGraphicsPipelineState = new (InCheckCmdList->Alloc<FComputedGraphicsPipelineState>()) FComputedGraphicsPipelineState; } }; struct FLocalGraphicsPipelineState { FLocalGraphicsPipelineStateWorkArea* WorkArea; FGraphicsPipelineStateRHIRef BypassGraphicsPipelineState; // this is only used in the case of Bypass, should eventually be deleted FLocalGraphicsPipelineState() : WorkArea(nullptr) { } FLocalGraphicsPipelineState(const FLocalGraphicsPipelineState& Other) : WorkArea(Other.WorkArea) , BypassGraphicsPipelineState(Other.BypassGraphicsPipelineState) { } }; struct FRHICommandBuildLocalGraphicsPipelineState : public FRHICommand<FRHICommandBuildLocalGraphicsPipelineState> { FLocalGraphicsPipelineStateWorkArea WorkArea; FORCEINLINE_DEBUGGABLE FRHICommandBuildLocalGraphicsPipelineState( FRHICommandListBase* CheckCmdList, const FGraphicsPipelineStateInitializer& Initializer ) : WorkArea(CheckCmdList, Initializer) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandSetLocalGraphicsPipelineState : public FRHICommand<FRHICommandSetLocalGraphicsPipelineState> { FLocalGraphicsPipelineState LocalGraphicsPipelineState; FORCEINLINE_DEBUGGABLE FRHICommandSetLocalGraphicsPipelineState(FRHICommandListBase* CheckCmdList, FLocalGraphicsPipelineState& InLocalGraphicsPipelineState) : LocalGraphicsPipelineState(InLocalGraphicsPipelineState) { check(CheckCmdList == LocalGraphicsPipelineState.WorkArea->CheckCmdList && CheckCmdList->GetUID() == LocalGraphicsPipelineState.WorkArea->UID); // this PSO was not built for this particular commandlist LocalGraphicsPipelineState.WorkArea->ComputedGraphicsPipelineState->UseCount++; } RHI_API void Execute(FRHICommandListBase& CmdList); }; // NVCHANGE_BEGIN: Nvidia Volumetric Lighting #if WITH_NVVOLUMETRICLIGHTING struct FRHICommandBeginAccumulation : public FRHICommand<FRHICommandBeginAccumulation> { FTextureRHIParamRef SceneDepthTextureRHI; TArray<NvVl::ViewerDesc> ViewerDescs; NvVl::MediumDesc MediumDesc; NvVl::DebugFlags DebugFlags; FORCEINLINE_DEBUGGABLE FRHICommandBeginAccumulation(FTextureRHIParamRef InSceneDepthTextureRHI, const TArray<NvVl::ViewerDesc>& InViewerDescs, const NvVl::MediumDesc& InMediumDesc, NvVl::DebugFlags InDebugFlags) : SceneDepthTextureRHI(InSceneDepthTextureRHI) , ViewerDescs(InViewerDescs) , MediumDesc(InMediumDesc) , DebugFlags(InDebugFlags) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandRenderVolume : public FRHICommand<FRHICommandRenderVolume> { TArray<FTextureRHIParamRef> ShadowMapTextures; NvVl::ShadowMapDesc ShadowMapDesc; NvVl::LightDesc LightDesc; NvVl::VolumeDesc VolumeDesc; FORCEINLINE_DEBUGGABLE FRHICommandRenderVolume(const TArray<FTextureRHIParamRef>& InShadowMapTextures, const NvVl::ShadowMapDesc& InShadowMapDesc, const NvVl::LightDesc& InLightDesc, const NvVl::VolumeDesc& InVolumeDesc) : ShadowMapTextures(InShadowMapTextures) , ShadowMapDesc(InShadowMapDesc) , LightDesc(InLightDesc) , VolumeDesc(InVolumeDesc) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandEndAccumulation : public FRHICommand<FRHICommandEndAccumulation> { FORCEINLINE_DEBUGGABLE FRHICommandEndAccumulation() { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandApplyLighting : public FRHICommand<FRHICommandApplyLighting> { FTextureRHIParamRef SceneColorSurfaceRHI; NvVl::PostprocessDesc PostprocessDesc; FORCEINLINE_DEBUGGABLE FRHICommandApplyLighting(FTextureRHIParamRef InSceneColorSurfaceRHI, const NvVl::PostprocessDesc& InPostprocessDesc) : SceneColorSurfaceRHI(InSceneColorSurfaceRHI) , PostprocessDesc(InPostprocessDesc) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; #endif // NVCHANGE_END: Nvidia Volumetric Lighting struct FComputedUniformBuffer { FUniformBufferRHIRef UniformBuffer; mutable int32 UseCount; FComputedUniformBuffer() : UseCount(0) { } }; struct FLocalUniformBufferWorkArea { void* Contents; const FRHIUniformBufferLayout* Layout; FComputedUniformBuffer* ComputedUniformBuffer; #if DO_CHECK // the below variables are used in check(), which can be enabled in Shipping builds (see Build.h) FRHICommandListBase* CheckCmdList; int32 UID; #endif FLocalUniformBufferWorkArea(FRHICommandListBase* InCheckCmdList, const void* InContents, uint32 ContentsSize, const FRHIUniformBufferLayout* InLayout) : Layout(InLayout) #if DO_CHECK , CheckCmdList(InCheckCmdList) , UID(InCheckCmdList->GetUID()) #endif { check(ContentsSize); Contents = InCheckCmdList->Alloc(ContentsSize, UNIFORM_BUFFER_STRUCT_ALIGNMENT); FMemory::Memcpy(Contents, InContents, ContentsSize); ComputedUniformBuffer = new (InCheckCmdList->Alloc<FComputedUniformBuffer>()) FComputedUniformBuffer; } }; struct FLocalUniformBuffer { FLocalUniformBufferWorkArea* WorkArea; FUniformBufferRHIRef BypassUniform; // this is only used in the case of Bypass, should eventually be deleted FLocalUniformBuffer() : WorkArea(nullptr) { } FLocalUniformBuffer(const FLocalUniformBuffer& Other) : WorkArea(Other.WorkArea) , BypassUniform(Other.BypassUniform) { } FORCEINLINE_DEBUGGABLE bool IsValid() const { return WorkArea || IsValidRef(BypassUniform); } }; struct FRHICommandBuildLocalUniformBuffer : public FRHICommand<FRHICommandBuildLocalUniformBuffer> { FLocalUniformBufferWorkArea WorkArea; FORCEINLINE_DEBUGGABLE FRHICommandBuildLocalUniformBuffer( FRHICommandListBase* CheckCmdList, const void* Contents, uint32 ContentsSize, const FRHIUniformBufferLayout& Layout ) : WorkArea(CheckCmdList, Contents, ContentsSize, &Layout) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; template <typename TShaderRHIParamRef> struct FRHICommandSetLocalUniformBuffer : public FRHICommand<FRHICommandSetLocalUniformBuffer<TShaderRHIParamRef> > { TShaderRHIParamRef Shader; uint32 BaseIndex; FLocalUniformBuffer LocalUniformBuffer; FORCEINLINE_DEBUGGABLE FRHICommandSetLocalUniformBuffer(FRHICommandListBase* CheckCmdList, TShaderRHIParamRef InShader, uint32 InBaseIndex, const FLocalUniformBuffer& InLocalUniformBuffer) : Shader(InShader) , BaseIndex(InBaseIndex) , LocalUniformBuffer(InLocalUniformBuffer) { check(CheckCmdList == LocalUniformBuffer.WorkArea->CheckCmdList && CheckCmdList->GetUID() == LocalUniformBuffer.WorkArea->UID); // this uniform buffer was not built for this particular commandlist LocalUniformBuffer.WorkArea->ComputedUniformBuffer->UseCount++; } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandBeginRenderQuery : public FRHICommand<FRHICommandBeginRenderQuery> { FRenderQueryRHIParamRef RenderQuery; FORCEINLINE_DEBUGGABLE FRHICommandBeginRenderQuery(FRenderQueryRHIParamRef InRenderQuery) : RenderQuery(InRenderQuery) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandEndRenderQuery : public FRHICommand<FRHICommandEndRenderQuery> { FRenderQueryRHIParamRef RenderQuery; FORCEINLINE_DEBUGGABLE FRHICommandEndRenderQuery(FRenderQueryRHIParamRef InRenderQuery) : RenderQuery(InRenderQuery) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandBeginOcclusionQueryBatch : public FRHICommand<FRHICommandBeginOcclusionQueryBatch> { FORCEINLINE_DEBUGGABLE FRHICommandBeginOcclusionQueryBatch() { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandEndOcclusionQueryBatch : public FRHICommand<FRHICommandEndOcclusionQueryBatch> { FORCEINLINE_DEBUGGABLE FRHICommandEndOcclusionQueryBatch() { } RHI_API void Execute(FRHICommandListBase& CmdList); }; template<ECmdList CmdListType> struct FRHICommandSubmitCommandsHint : public FRHICommand<FRHICommandSubmitCommandsHint<CmdListType>> { FORCEINLINE_DEBUGGABLE FRHICommandSubmitCommandsHint() { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandBeginScene : public FRHICommand<FRHICommandBeginScene> { FORCEINLINE_DEBUGGABLE FRHICommandBeginScene() { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandEndScene : public FRHICommand<FRHICommandEndScene> { FORCEINLINE_DEBUGGABLE FRHICommandEndScene() { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandBeginFrame : public FRHICommand<FRHICommandBeginFrame> { FORCEINLINE_DEBUGGABLE FRHICommandBeginFrame() { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandEndFrame : public FRHICommand<FRHICommandEndFrame> { FORCEINLINE_DEBUGGABLE FRHICommandEndFrame() { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandBeginDrawingViewport : public FRHICommand<FRHICommandBeginDrawingViewport> { FViewportRHIParamRef Viewport; FTextureRHIParamRef RenderTargetRHI; FORCEINLINE_DEBUGGABLE FRHICommandBeginDrawingViewport(FViewportRHIParamRef InViewport, FTextureRHIParamRef InRenderTargetRHI) : Viewport(InViewport) , RenderTargetRHI(InRenderTargetRHI) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandEndDrawingViewport : public FRHICommand<FRHICommandEndDrawingViewport> { FViewportRHIParamRef Viewport; bool bPresent; bool bLockToVsync; FORCEINLINE_DEBUGGABLE FRHICommandEndDrawingViewport(FViewportRHIParamRef InViewport, bool InbPresent, bool InbLockToVsync) : Viewport(InViewport) , bPresent(InbPresent) , bLockToVsync(InbLockToVsync) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; template<ECmdList CmdListType> struct FRHICommandPushEvent : public FRHICommand<FRHICommandPushEvent<CmdListType>> { const TCHAR *Name; FColor Color; FORCEINLINE_DEBUGGABLE FRHICommandPushEvent(const TCHAR *InName, FColor InColor) : Name(InName) , Color(InColor) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; template<ECmdList CmdListType> struct FRHICommandPopEvent : public FRHICommand<FRHICommandPopEvent<CmdListType>> { RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandInvalidateCachedState : public FRHICommand<FRHICommandInvalidateCachedState> { RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICommandDebugBreak : public FRHICommand<FRHICommandDebugBreak> { void Execute(FRHICommandListBase& CmdList) { if (FPlatformMisc::IsDebuggerPresent()) { FPlatformMisc::DebugBreak(); } } }; struct FRHICommandUpdateTextureReference : public FRHICommand<FRHICommandUpdateTextureReference> { FTextureReferenceRHIParamRef TextureRef; FTextureRHIParamRef NewTexture; FORCEINLINE_DEBUGGABLE FRHICommandUpdateTextureReference(FTextureReferenceRHIParamRef InTextureRef, FTextureRHIParamRef InNewTexture) : TextureRef(InTextureRef) , NewTexture(InNewTexture) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; // NvFlow begin struct FRHICommandNvFlowWork : public FRHICommand<FRHICommandNvFlowWork> { void(*WorkFunc)(void*,SIZE_T,IRHICommandContext*); void* ParamData; SIZE_T NumBytes; FORCEINLINE_DEBUGGABLE FRHICommandNvFlowWork(void(*WorkFunc)(void*,SIZE_T,IRHICommandContext*), void* ParamData, SIZE_T NumBytes) : WorkFunc(WorkFunc) , ParamData(ParamData) , NumBytes(NumBytes) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; // NvFlow end #define CMD_CONTEXT(Method) GetContext().Method #define COMPUTE_CONTEXT(Method) GetComputeContext().Method // NVCHANGE_BEGIN: Add HBAO+ #if WITH_GFSDK_SSAO struct FRHICommandRenderHBAO : public FRHICommand<FRHICommandRenderHBAO> { FTextureRHIParamRef SceneDepthTextureRHI; FMatrix ProjectionMatrix; FTextureRHIParamRef SceneNormalTextureRHI; FMatrix ViewMatrix; FTextureRHIParamRef SceneColorTextureRHI; GFSDK_SSAO_Parameters AOParams; FORCEINLINE_DEBUGGABLE FRHICommandRenderHBAO( const FTextureRHIParamRef InSceneDepthTextureRHI, const FMatrix& InProjectionMatrix, const FTextureRHIParamRef InSceneNormalTextureRHI, const FMatrix& InViewMatrix, const FTextureRHIParamRef InSceneColorTextureRHI, const GFSDK_SSAO_Parameters& InAOParams ) : SceneDepthTextureRHI(InSceneDepthTextureRHI) , ProjectionMatrix(InProjectionMatrix) , SceneNormalTextureRHI(InSceneNormalTextureRHI) , ViewMatrix(InViewMatrix) , SceneColorTextureRHI(InSceneColorTextureRHI) , AOParams(InAOParams) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; #endif // NVCHANGE_END: Add HBAO+ // NVCHANGE_BEGIN: Add VXGI #if WITH_GFSDK_VXGI struct FRHIVXGICleanupAfterVoxelization : public FRHICommand<FRHIVXGICleanupAfterVoxelization> { FORCEINLINE_DEBUGGABLE FRHIVXGICleanupAfterVoxelization() { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHISetViewportsAndScissorRects : public FRHICommand<FRHISetViewportsAndScissorRects> { uint32 Count; TArray<FViewportBounds> Viewports; TArray<FScissorRect> ScissorRects; FORCEINLINE_DEBUGGABLE FRHISetViewportsAndScissorRects(uint32 InCount, const FViewportBounds* InViewports, const FScissorRect* InScissorRects) { Count = InCount; Viewports.SetNum(Count); ScissorRects.SetNum(Count); FMemory::Memmove(Viewports.GetData(), InViewports, Count * sizeof(FViewportBounds)); FMemory::Memmove(ScissorRects.GetData(), InScissorRects, Count * sizeof(FScissorRect)); } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHIDispatchIndirectComputeShaderStructured : public FRHICommand<FRHIDispatchIndirectComputeShaderStructured> { FStructuredBufferRHIRef ArgumentBuffer; uint32 ArgumentOffset; FORCEINLINE_DEBUGGABLE FRHIDispatchIndirectComputeShaderStructured(FStructuredBufferRHIParamRef InArgumentBuffer, uint32 InArgumentOffset) : ArgumentBuffer(InArgumentBuffer) , ArgumentOffset(InArgumentOffset) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHICopyStructuredBufferData : public FRHICommand<FRHICopyStructuredBufferData> { FStructuredBufferRHIRef DestBuffer; uint32 DestOffset; FStructuredBufferRHIRef SrcBuffer; uint32 SrcOffset; uint32 DataSize; FORCEINLINE_DEBUGGABLE FRHICopyStructuredBufferData( FStructuredBufferRHIParamRef InDestBuffer, uint32 InDestOffset, FStructuredBufferRHIParamRef InSrcBuffer, uint32 InSrcOffset, uint32 InDataSize ) : DestBuffer(InDestBuffer) , DestOffset(InDestOffset) , SrcBuffer(InSrcBuffer) , SrcOffset(InSrcOffset) , DataSize(InDataSize) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; struct FRHIExecuteVxgiRenderingCommand : public FRHICommand<FRHIExecuteVxgiRenderingCommand> { NVRHI::IRenderThreadCommand* Command; FORCEINLINE_DEBUGGABLE FRHIExecuteVxgiRenderingCommand( NVRHI::IRenderThreadCommand* InCommand ) : Command(InCommand) { } RHI_API void Execute(FRHICommandListBase& CmdList); }; #endif // NVCHANGE_END: Add VXGI template<> void FRHICommandSetShaderParameter<FComputeShaderRHIParamRef, ECmdList::ECompute>::Execute(FRHICommandListBase& CmdList); template<> void FRHICommandSetShaderUniformBuffer<FComputeShaderRHIParamRef, ECmdList::ECompute>::Execute(FRHICommandListBase& CmdList); template<> void FRHICommandSetShaderTexture<FComputeShaderRHIParamRef, ECmdList::ECompute>::Execute(FRHICommandListBase& CmdList); template<> void FRHICommandSetShaderResourceViewParameter<FComputeShaderRHIParamRef, ECmdList::ECompute>::Execute(FRHICommandListBase& CmdList); template<> void FRHICommandSetShaderSampler<FComputeShaderRHIParamRef, ECmdList::ECompute>::Execute(FRHICommandListBase& CmdList); class RHI_API FRHIRenderPassCommandList : public FRHICommandListBase { public: /** Custom new/delete with recycling */ void* operator new(size_t Size); void operator delete(void *RawMemory); FRHICommandList& GetParent() { return *(FRHICommandList*)this; } FORCEINLINE_DEBUGGABLE void BeginUpdateMultiFrameResource(FTextureRHIParamRef Texture) { if (Bypass()) { CMD_CONTEXT(RHIBeginUpdateMultiFrameResource)(Texture); return; } new (AllocCommand<FRHICommandBeginUpdateMultiFrameResource>()) FRHICommandBeginUpdateMultiFrameResource(Texture); } FORCEINLINE_DEBUGGABLE void EndUpdateMultiFrameResource(FTextureRHIParamRef Texture) { if (Bypass()) { CMD_CONTEXT(RHIEndUpdateMultiFrameResource)(Texture); return; } new (AllocCommand<FRHICommandEndUpdateMultiFrameResource>()) FRHICommandEndUpdateMultiFrameResource(Texture); } FORCEINLINE_DEBUGGABLE void BeginUpdateMultiFrameResource(FUnorderedAccessViewRHIParamRef UAV) { if (Bypass()) { CMD_CONTEXT(RHIBeginUpdateMultiFrameResource)(UAV); return; } new (AllocCommand<FRHICommandBeginUpdateMultiFrameUAV>()) FRHICommandBeginUpdateMultiFrameUAV(UAV); } FORCEINLINE_DEBUGGABLE void EndUpdateMultiFrameResource(FUnorderedAccessViewRHIParamRef UAV) { if (Bypass()) { CMD_CONTEXT(RHIEndUpdateMultiFrameResource)(UAV); return; } new (AllocCommand<FRHICommandEndUpdateMultiFrameUAV>()) FRHICommandEndUpdateMultiFrameUAV(UAV); } FORCEINLINE_DEBUGGABLE FLocalGraphicsPipelineState BuildLocalGraphicsPipelineState( const FGraphicsPipelineStateInitializer& Initializer ) { FLocalGraphicsPipelineState Result; if (Bypass()) { Result.BypassGraphicsPipelineState = RHICreateGraphicsPipelineState(Initializer); } else { auto* Cmd = new (AllocCommand<FRHICommandBuildLocalGraphicsPipelineState>()) FRHICommandBuildLocalGraphicsPipelineState(this, Initializer); Result.WorkArea = &Cmd->WorkArea; } return Result; } FORCEINLINE_DEBUGGABLE void SetLocalGraphicsPipelineState(FLocalGraphicsPipelineState LocalGraphicsPipelineState) { if (Bypass()) { CMD_CONTEXT(RHISetGraphicsPipelineState)(LocalGraphicsPipelineState.BypassGraphicsPipelineState); return; } new (AllocCommand<FRHICommandSetLocalGraphicsPipelineState>()) FRHICommandSetLocalGraphicsPipelineState(this, LocalGraphicsPipelineState); } FORCEINLINE_DEBUGGABLE FLocalUniformBuffer BuildLocalUniformBuffer(const void* Contents, uint32 ContentsSize, const FRHIUniformBufferLayout& Layout) { FLocalUniformBuffer Result; if (Bypass()) { Result.BypassUniform = RHICreateUniformBuffer(Contents, Layout, UniformBuffer_SingleFrame); } else { check(Contents && ContentsSize && (&Layout != nullptr)); auto* Cmd = new (AllocCommand<FRHICommandBuildLocalUniformBuffer>()) FRHICommandBuildLocalUniformBuffer(this, Contents, ContentsSize, Layout); Result.WorkArea = &Cmd->WorkArea; } return Result; } template <typename TShaderRHIParamRef> FORCEINLINE_DEBUGGABLE void SetLocalShaderUniformBuffer(TShaderRHIParamRef Shader, uint32 BaseIndex, const FLocalUniformBuffer& UniformBuffer) { if (Bypass()) { CMD_CONTEXT(RHISetShaderUniformBuffer)(Shader, BaseIndex, UniformBuffer.BypassUniform); return; } new (AllocCommand<FRHICommandSetLocalUniformBuffer<TShaderRHIParamRef> >()) FRHICommandSetLocalUniformBuffer<TShaderRHIParamRef>(this, Shader, BaseIndex, UniformBuffer); } template <typename TShaderRHI> FORCEINLINE_DEBUGGABLE void SetLocalShaderUniformBuffer(TRefCountPtr<TShaderRHI>& Shader, uint32 BaseIndex, const FLocalUniformBuffer& UniformBuffer) { SetLocalShaderUniformBuffer(Shader.GetReference(), BaseIndex, UniformBuffer); } template <typename TShaderRHI> FORCEINLINE_DEBUGGABLE void SetShaderUniformBuffer(TShaderRHI* Shader, uint32 BaseIndex, FUniformBufferRHIParamRef UniformBuffer) { if (Bypass()) { CMD_CONTEXT(RHISetShaderUniformBuffer)(Shader, BaseIndex, UniformBuffer); return; } new (AllocCommand<FRHICommandSetShaderUniformBuffer<TShaderRHI*, ECmdList::EGfx> >()) FRHICommandSetShaderUniformBuffer<TShaderRHI*, ECmdList::EGfx>(Shader, BaseIndex, UniformBuffer); } template <typename TShaderRHI> FORCEINLINE void SetShaderUniformBuffer(TRefCountPtr<TShaderRHI>& Shader, uint32 BaseIndex, FUniformBufferRHIParamRef UniformBuffer) { SetShaderUniformBuffer(Shader.GetReference(), BaseIndex, UniformBuffer); } template <typename TShaderRHI> FORCEINLINE_DEBUGGABLE void SetShaderParameter(TShaderRHI* Shader, uint32 BufferIndex, uint32 BaseIndex, uint32 NumBytes, const void* NewValue) { if (Bypass()) { CMD_CONTEXT(RHISetShaderParameter)(Shader, BufferIndex, BaseIndex, NumBytes, NewValue); return; } void* UseValue = Alloc(NumBytes, 16); FMemory::Memcpy(UseValue, NewValue, NumBytes); new (AllocCommand<FRHICommandSetShaderParameter<TShaderRHI*, ECmdList::EGfx> >()) FRHICommandSetShaderParameter<TShaderRHI*, ECmdList::EGfx>(Shader, BufferIndex, BaseIndex, NumBytes, UseValue); } template <typename TShaderRHI> FORCEINLINE void SetShaderParameter(TRefCountPtr<TShaderRHI>& Shader, uint32 BufferIndex, uint32 BaseIndex, uint32 NumBytes, const void* NewValue) { SetShaderParameter(Shader.GetReference(), BufferIndex, BaseIndex, NumBytes, NewValue); } template <typename TShaderRHIParamRef> FORCEINLINE_DEBUGGABLE void SetShaderTexture(TShaderRHIParamRef Shader, uint32 TextureIndex, FTextureRHIParamRef Texture) { if (Bypass()) { CMD_CONTEXT(RHISetShaderTexture)(Shader, TextureIndex, Texture); return; } new (AllocCommand<FRHICommandSetShaderTexture<TShaderRHIParamRef, ECmdList::EGfx> >()) FRHICommandSetShaderTexture<TShaderRHIParamRef, ECmdList::EGfx>(Shader, TextureIndex, Texture); } template <typename TShaderRHI> FORCEINLINE_DEBUGGABLE void SetShaderTexture(TRefCountPtr<TShaderRHI>& Shader, uint32 TextureIndex, FTextureRHIParamRef Texture) { SetShaderTexture(Shader.GetReference(), TextureIndex, Texture); } template <typename TShaderRHIParamRef> FORCEINLINE_DEBUGGABLE void SetShaderResourceViewParameter(TShaderRHIParamRef Shader, uint32 SamplerIndex, FShaderResourceViewRHIParamRef SRV) { if (Bypass()) { CMD_CONTEXT(RHISetShaderResourceViewParameter)(Shader, SamplerIndex, SRV); return; } new (AllocCommand<FRHICommandSetShaderResourceViewParameter<TShaderRHIParamRef, ECmdList::EGfx> >()) FRHICommandSetShaderResourceViewParameter<TShaderRHIParamRef, ECmdList::EGfx>(Shader, SamplerIndex, SRV); } template <typename TShaderRHI> FORCEINLINE_DEBUGGABLE void SetShaderResourceViewParameter(TRefCountPtr<TShaderRHI>& Shader, uint32 SamplerIndex, FShaderResourceViewRHIParamRef SRV) { SetShaderResourceViewParameter(Shader.GetReference(), SamplerIndex, SRV); } template <typename TShaderRHIParamRef> FORCEINLINE_DEBUGGABLE void SetShaderSampler(TShaderRHIParamRef Shader, uint32 SamplerIndex, FSamplerStateRHIParamRef State) { if (Bypass()) { CMD_CONTEXT(RHISetShaderSampler)(Shader, SamplerIndex, State); return; } new (AllocCommand<FRHICommandSetShaderSampler<TShaderRHIParamRef, ECmdList::EGfx> >()) FRHICommandSetShaderSampler<TShaderRHIParamRef, ECmdList::EGfx>(Shader, SamplerIndex, State); } template <typename TShaderRHI> FORCEINLINE_DEBUGGABLE void SetShaderSampler(TRefCountPtr<TShaderRHI>& Shader, uint32 SamplerIndex, FSamplerStateRHIParamRef State) { SetShaderSampler(Shader.GetReference(), SamplerIndex, State); } FORCEINLINE_DEBUGGABLE void SetUAVParameter(FComputeShaderRHIParamRef Shader, uint32 UAVIndex, FUnorderedAccessViewRHIParamRef UAV) { if (Bypass()) { CMD_CONTEXT(RHISetUAVParameter)(Shader, UAVIndex, UAV); return; } new (AllocCommand<FRHICommandSetUAVParameter<FComputeShaderRHIParamRef, ECmdList::EGfx> >()) FRHICommandSetUAVParameter<FComputeShaderRHIParamRef, ECmdList::EGfx>(Shader, UAVIndex, UAV); } FORCEINLINE_DEBUGGABLE void SetUAVParameter(TRefCountPtr<FRHIComputeShader>& Shader, uint32 UAVIndex, FUnorderedAccessViewRHIParamRef UAV) { SetUAVParameter(Shader.GetReference(), UAVIndex, UAV); } FORCEINLINE_DEBUGGABLE void SetUAVParameter(FComputeShaderRHIParamRef Shader, uint32 UAVIndex, FUnorderedAccessViewRHIParamRef UAV, uint32 InitialCount) { if (Bypass()) { CMD_CONTEXT(RHISetUAVParameter)(Shader, UAVIndex, UAV, InitialCount); return; } new (AllocCommand<FRHICommandSetUAVParameter_IntialCount<FComputeShaderRHIParamRef, ECmdList::EGfx> >()) FRHICommandSetUAVParameter_IntialCount<FComputeShaderRHIParamRef, ECmdList::EGfx>(Shader, UAVIndex, UAV, InitialCount); } FORCEINLINE_DEBUGGABLE void SetUAVParameter(TRefCountPtr<FRHIComputeShader>& Shader, uint32 UAVIndex, FUnorderedAccessViewRHIParamRef UAV, uint32 InitialCount) { SetUAVParameter(Shader.GetReference(), UAVIndex, UAV, InitialCount); } FORCEINLINE_DEBUGGABLE void SetBlendFactor(const FLinearColor& BlendFactor = FLinearColor::White) { if (Bypass()) { CMD_CONTEXT(RHISetBlendFactor)(BlendFactor); return; } new (AllocCommand<FRHICommandSetBlendFactor>()) FRHICommandSetBlendFactor(BlendFactor); } FORCEINLINE_DEBUGGABLE void DrawPrimitive(uint32 PrimitiveType, uint32 BaseVertexIndex, uint32 NumPrimitives, uint32 NumInstances) { if (Bypass()) { CMD_CONTEXT(RHIDrawPrimitive)(PrimitiveType, BaseVertexIndex, NumPrimitives, NumInstances); return; } new (AllocCommand<FRHICommandDrawPrimitive>()) FRHICommandDrawPrimitive(PrimitiveType, BaseVertexIndex, NumPrimitives, NumInstances); } FORCEINLINE_DEBUGGABLE void DrawIndexedPrimitive(FIndexBufferRHIParamRef IndexBuffer, uint32 PrimitiveType, int32 BaseVertexIndex, uint32 FirstInstance, uint32 NumVertices, uint32 StartIndex, uint32 NumPrimitives, uint32 NumInstances) { if (Bypass()) { CMD_CONTEXT(RHIDrawIndexedPrimitive)(IndexBuffer, PrimitiveType, BaseVertexIndex, FirstInstance, NumVertices, StartIndex, NumPrimitives, NumInstances); return; } new (AllocCommand<FRHICommandDrawIndexedPrimitive>()) FRHICommandDrawIndexedPrimitive(IndexBuffer, PrimitiveType, BaseVertexIndex, FirstInstance, NumVertices, StartIndex, NumPrimitives, NumInstances); } FORCEINLINE_DEBUGGABLE void SetStreamSource(uint32 StreamIndex, FVertexBufferRHIParamRef VertexBuffer, uint32 Offset) { if (Bypass()) { CMD_CONTEXT(RHISetStreamSource)(StreamIndex, VertexBuffer, Offset); return; } new (AllocCommand<FRHICommandSetStreamSource>()) FRHICommandSetStreamSource(StreamIndex, VertexBuffer, Offset); } FORCEINLINE_DEBUGGABLE void SetStencilRef(uint32 StencilRef) { if (Bypass()) { CMD_CONTEXT(RHISetStencilRef)(StencilRef); return; } new(AllocCommand<FRHICommandSetStencilRef>()) FRHICommandSetStencilRef(StencilRef); } FORCEINLINE_DEBUGGABLE void SetViewport(uint32 MinX, uint32 MinY, float MinZ, uint32 MaxX, uint32 MaxY, float MaxZ) { if (Bypass()) { CMD_CONTEXT(RHISetViewport)(MinX, MinY, MinZ, MaxX, MaxY, MaxZ); return; } new (AllocCommand<FRHICommandSetViewport>()) FRHICommandSetViewport(MinX, MinY, MinZ, MaxX, MaxY, MaxZ); } FORCEINLINE_DEBUGGABLE void SetStereoViewport(uint32 LeftMinX, uint32 RightMinX, uint32 LeftMinY, uint32 RightMinY, float MinZ, uint32 LeftMaxX, uint32 RightMaxX, uint32 LeftMaxY, uint32 RightMaxY, float MaxZ) { if (Bypass()) { CMD_CONTEXT(RHISetStereoViewport)(LeftMinX, RightMinX, LeftMinY, RightMinY, MinZ, LeftMaxX, RightMaxX, LeftMaxY, RightMaxY, MaxZ); return; } new (AllocCommand<FRHICommandSetStereoViewport>()) FRHICommandSetStereoViewport(LeftMinX, RightMinX, LeftMinY, RightMinY, MinZ, LeftMaxX, RightMaxX, LeftMaxY, RightMaxY, MaxZ); } FORCEINLINE_DEBUGGABLE void SetScissorRect(bool bEnable, uint32 MinX, uint32 MinY, uint32 MaxX, uint32 MaxY) { if (Bypass()) { CMD_CONTEXT(RHISetScissorRect)(bEnable, MinX, MinY, MaxX, MaxY); return; } new (AllocCommand<FRHICommandSetScissorRect>()) FRHICommandSetScissorRect(bEnable, MinX, MinY, MaxX, MaxY); } FORCEINLINE_DEBUGGABLE void BeginDrawPrimitiveUP(uint32 PrimitiveType, uint32 NumPrimitives, uint32 NumVertices, uint32 VertexDataStride, void*& OutVertexData) { if (Bypass()) { CMD_CONTEXT(RHIBeginDrawPrimitiveUP)(PrimitiveType, NumPrimitives, NumVertices, VertexDataStride, OutVertexData); return; } check(!DrawUPData.OutVertexData && NumVertices * VertexDataStride > 0); OutVertexData = Alloc(NumVertices * VertexDataStride, 16); DrawUPData.PrimitiveType = PrimitiveType; DrawUPData.NumPrimitives = NumPrimitives; DrawUPData.NumVertices = NumVertices; DrawUPData.VertexDataStride = VertexDataStride; DrawUPData.OutVertexData = OutVertexData; } FORCEINLINE_DEBUGGABLE void EndDrawPrimitiveUP() { if (Bypass()) { CMD_CONTEXT(RHIEndDrawPrimitiveUP)(); return; } check(DrawUPData.OutVertexData && DrawUPData.NumVertices); new (AllocCommand<FRHICommandEndDrawPrimitiveUP>()) FRHICommandEndDrawPrimitiveUP(DrawUPData.PrimitiveType, DrawUPData.NumPrimitives, DrawUPData.NumVertices, DrawUPData.VertexDataStride, DrawUPData.OutVertexData); DrawUPData.OutVertexData = nullptr; DrawUPData.NumVertices = 0; } FORCEINLINE_DEBUGGABLE void BeginDrawIndexedPrimitiveUP(uint32 PrimitiveType, uint32 NumPrimitives, uint32 NumVertices, uint32 VertexDataStride, void*& OutVertexData, uint32 MinVertexIndex, uint32 NumIndices, uint32 IndexDataStride, void*& OutIndexData) { if (Bypass()) { CMD_CONTEXT(RHIBeginDrawIndexedPrimitiveUP)(PrimitiveType, NumPrimitives, NumVertices, VertexDataStride, OutVertexData, MinVertexIndex, NumIndices, IndexDataStride, OutIndexData); return; } check(!DrawUPData.OutVertexData && !DrawUPData.OutIndexData && NumVertices * VertexDataStride > 0 && NumIndices * IndexDataStride > 0); OutVertexData = Alloc(NumVertices * VertexDataStride, 16); OutIndexData = Alloc(NumIndices * IndexDataStride, 16); DrawUPData.PrimitiveType = PrimitiveType; DrawUPData.NumPrimitives = NumPrimitives; DrawUPData.NumVertices = NumVertices; DrawUPData.VertexDataStride = VertexDataStride; DrawUPData.OutVertexData = OutVertexData; DrawUPData.MinVertexIndex = MinVertexIndex; DrawUPData.NumIndices = NumIndices; DrawUPData.IndexDataStride = IndexDataStride; DrawUPData.OutIndexData = OutIndexData; } FORCEINLINE_DEBUGGABLE void EndDrawIndexedPrimitiveUP() { if (Bypass()) { CMD_CONTEXT(RHIEndDrawIndexedPrimitiveUP)(); return; } check(DrawUPData.OutVertexData && DrawUPData.OutIndexData && DrawUPData.NumIndices && DrawUPData.NumVertices); new (AllocCommand<FRHICommandEndDrawIndexedPrimitiveUP>()) FRHICommandEndDrawIndexedPrimitiveUP(DrawUPData.PrimitiveType, DrawUPData.NumPrimitives, DrawUPData.NumVertices, DrawUPData.VertexDataStride, DrawUPData.OutVertexData, DrawUPData.MinVertexIndex, DrawUPData.NumIndices, DrawUPData.IndexDataStride, DrawUPData.OutIndexData); DrawUPData.OutVertexData = nullptr; DrawUPData.OutIndexData = nullptr; DrawUPData.NumIndices = 0; DrawUPData.NumVertices = 0; } FORCEINLINE_DEBUGGABLE void SetGraphicsPipelineState(class FGraphicsPipelineState* GraphicsPipelineState) { if (Bypass()) { extern RHI_API FRHIGraphicsPipelineState* ExecuteSetGraphicsPipelineState(class FGraphicsPipelineState* GraphicsPipelineState); FRHIGraphicsPipelineState* RHIGraphicsPipelineState = ExecuteSetGraphicsPipelineState(GraphicsPipelineState); CMD_CONTEXT(RHISetGraphicsPipelineState)(RHIGraphicsPipelineState); return; } new (AllocCommand<FRHICommandSetGraphicsPipelineState>()) FRHICommandSetGraphicsPipelineState(GraphicsPipelineState); } FORCEINLINE_DEBUGGABLE void DrawPrimitiveIndirect(uint32 PrimitiveType, FVertexBufferRHIParamRef ArgumentBuffer, uint32 ArgumentOffset) { if (Bypass()) { CMD_CONTEXT(RHIDrawPrimitiveIndirect)(PrimitiveType, ArgumentBuffer, ArgumentOffset); return; } new (AllocCommand<FRHICommandDrawPrimitiveIndirect>()) FRHICommandDrawPrimitiveIndirect(PrimitiveType, ArgumentBuffer, ArgumentOffset); } FORCEINLINE_DEBUGGABLE void DrawIndexedIndirect(FIndexBufferRHIParamRef IndexBufferRHI, uint32 PrimitiveType, FStructuredBufferRHIParamRef ArgumentsBufferRHI, uint32 DrawArgumentsIndex, uint32 NumInstances) { if (Bypass()) { CMD_CONTEXT(RHIDrawIndexedIndirect)(IndexBufferRHI, PrimitiveType, ArgumentsBufferRHI, DrawArgumentsIndex, NumInstances); return; } new (AllocCommand<FRHICommandDrawIndexedIndirect>()) FRHICommandDrawIndexedIndirect(IndexBufferRHI, PrimitiveType, ArgumentsBufferRHI, DrawArgumentsIndex, NumInstances); } FORCEINLINE_DEBUGGABLE void DrawIndexedPrimitiveIndirect(uint32 PrimitiveType, FIndexBufferRHIParamRef IndexBuffer, FVertexBufferRHIParamRef ArgumentsBuffer, uint32 ArgumentOffset) { if (Bypass()) { CMD_CONTEXT(RHIDrawIndexedPrimitiveIndirect)(PrimitiveType, IndexBuffer, ArgumentsBuffer, ArgumentOffset); return; } new (AllocCommand<FRHICommandDrawIndexedPrimitiveIndirect>()) FRHICommandDrawIndexedPrimitiveIndirect(PrimitiveType, IndexBuffer, ArgumentsBuffer, ArgumentOffset); } FORCEINLINE_DEBUGGABLE void EnableDepthBoundsTest(bool bEnable, float MinDepth, float MaxDepth) { if (Bypass()) { CMD_CONTEXT(RHIEnableDepthBoundsTest)(bEnable, MinDepth, MaxDepth); return; } new (AllocCommand<FRHICommandEnableDepthBoundsTest>()) FRHICommandEnableDepthBoundsTest(bEnable, MinDepth, MaxDepth); } FORCEINLINE_DEBUGGABLE void PushEvent(const TCHAR* Name, FColor Color) { if (Bypass()) { CMD_CONTEXT(RHIPushEvent)(Name, Color); return; } TCHAR* NameCopy = AllocString(Name); new (AllocCommand<FRHICommandPushEvent<ECmdList::EGfx>>()) FRHICommandPushEvent<ECmdList::EGfx>(NameCopy, Color); } FORCEINLINE_DEBUGGABLE void PopEvent() { if (Bypass()) { CMD_CONTEXT(RHIPopEvent)(); return; } new (AllocCommand<FRHICommandPopEvent<ECmdList::EGfx>>()) FRHICommandPopEvent<ECmdList::EGfx>(); } FORCEINLINE_DEBUGGABLE void BeginRenderQuery(FRenderQueryRHIParamRef RenderQuery) { if (Bypass()) { CMD_CONTEXT(RHIBeginRenderQuery)(RenderQuery); return; } new (AllocCommand<FRHICommandBeginRenderQuery>()) FRHICommandBeginRenderQuery(RenderQuery); } FORCEINLINE_DEBUGGABLE void EndRenderQuery(FRenderQueryRHIParamRef RenderQuery) { if (Bypass()) { CMD_CONTEXT(RHIEndRenderQuery)(RenderQuery); return; } new (AllocCommand<FRHICommandEndRenderQuery>()) FRHICommandEndRenderQuery(RenderQuery); } FORCEINLINE_DEBUGGABLE void BeginOcclusionQueryBatch() { if (Bypass()) { CMD_CONTEXT(RHIBeginOcclusionQueryBatch)(); return; } new (AllocCommand<FRHICommandBeginOcclusionQueryBatch>()) FRHICommandBeginOcclusionQueryBatch(); } FORCEINLINE_DEBUGGABLE void EndOcclusionQueryBatch() { if (Bypass()) { CMD_CONTEXT(RHIEndOcclusionQueryBatch)(); return; } new (AllocCommand<FRHICommandEndOcclusionQueryBatch>()) FRHICommandEndOcclusionQueryBatch(); } FORCEINLINE_DEBUGGABLE void BreakPoint() { #if !UE_BUILD_SHIPPING if (Bypass()) { if (FPlatformMisc::IsDebuggerPresent()) { FPlatformMisc::DebugBreak(); } return; } new (AllocCommand<FRHICommandDebugBreak>()) FRHICommandDebugBreak(); #endif } void ApplyCachedRenderTargets(FGraphicsPipelineStateInitializer& GraphicsPSOInit); FRHIRenderPassCommandList(FRHICommandList& InParent) { // Separate constructor since we want to call the base one Data.Parent = (FRHICommandListBase*)&InParent; } friend class FRHICommandList; }; class RHI_API FRHIRenderSubPassCommandList : public FRHIRenderPassCommandList { public: FRHIRenderSubPassCommandList(FRHICommandList& InParent, FRHIParallelRenderPassCommandList* InRenderPass) : FRHIRenderPassCommandList(InParent) { Data.LocalRHIRenderSubPass = new(Alloc<FLocalCmdListRenderSubPass>()) FLocalCmdListRenderSubPass; Data.Type = FRHICommandListBase::FCommonData::ECmdListType::RenderSubPass; } FRHIParallelRenderPassCommandList& GetParent() { return *(FRHIParallelRenderPassCommandList*)Data.Parent; } ~FRHIRenderSubPassCommandList() { //check(bEnded); FRHIRenderPassCommandList::~FRHIRenderPassCommandList(); } /** Custom new/delete with recycling */ void* operator new(size_t Size); void operator delete(void *RawMemory); }; class RHI_API FRHIParallelRenderPassCommandList : public FRHIRenderPassCommandList { public: FRHIParallelRenderPassCommandList(FRHICommandList& InParent) : FRHIRenderPassCommandList(InParent) { Data.LocalRHIParallelRenderPass = new(Alloc<FLocalCmdListParallelRenderPass>()) FLocalCmdListParallelRenderPass; } /** Custom new/delete with recycling */ void* operator new(size_t Size); void operator delete(void *RawMemory); FRHIRenderSubPassCommandList& BeginSubpass() { FRHIRenderSubPassCommandList* SubPass = new FRHIRenderSubPassCommandList(GetParent(), this); //SubRenderPasses.Add(SubPass); if (Bypass()) { SubPass->Data.LocalRHIRenderSubPass->RenderSubPass = CMD_CONTEXT(RHIBeginRenderSubPass)(Data.LocalRHIParallelRenderPass->RenderPass); } else { new (AllocCommand<FRHICommandBeginRenderSubPass>()) FRHICommandBeginRenderSubPass(Data.LocalRHIParallelRenderPass, SubPass->Data.LocalRHIRenderSubPass); } return *SubPass; } void EndSubpass(FRHIRenderSubPassCommandList& SubPass) { //int32 Index = SubRenderPasses.Find(&SubPass); //ensure(Index != INDEX_NONE); //check(!SubPass.bEnded); if (Bypass()) { CMD_CONTEXT(RHIEndRenderSubPass)(Data.LocalRHIParallelRenderPass->RenderPass, SubPass.Data.LocalRHIRenderSubPass->RenderSubPass); delete &SubPass; } else { new (AllocCommand<FRHICommandEndRenderSubPass>()) FRHICommandEndRenderSubPass(Data.LocalRHIParallelRenderPass, SubPass.Data.LocalRHIRenderSubPass); } //SubPass.bEnded = true; } }; class RHI_API FRHICommandList : public FRHICommandListBase { public: /** Custom new/delete with recycling */ void* operator new(size_t Size); void operator delete(void *RawMemory); inline bool IsOutsideRenderPass() const { return Data.LocalRHIRenderPass == nullptr && Data.LocalRHIParallelRenderPass == nullptr; } // WaveWorks Begin FORCEINLINE_DEBUGGABLE void DrawQuadTreeWaveWorks(FWaveWorksRHIRef waveWorks, struct GFSDK_WaveWorks_Quadtree* QuadTreeHandle, FMatrix ViewMatrix, FMatrix ProjMatrix, const TArray<uint32>& ShaderInputMappings) { if (Bypass()) { waveWorks->DrawQuadTree( QuadTreeHandle, ViewMatrix, ProjMatrix, ShaderInputMappings ); } else { new (AllocCommand<FRHICommandBuildDrawQuadTreeWaveWorks>()) FRHICommandBuildDrawQuadTreeWaveWorks(this, waveWorks, QuadTreeHandle, ViewMatrix, ProjMatrix, ShaderInputMappings); } } // WaveWorks End FORCEINLINE_DEBUGGABLE void BeginUpdateMultiFrameResource( FTextureRHIParamRef Texture) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHIBeginUpdateMultiFrameResource)( Texture); return; } new (AllocCommand<FRHICommandBeginUpdateMultiFrameResource>()) FRHICommandBeginUpdateMultiFrameResource( Texture); } FORCEINLINE_DEBUGGABLE void EndUpdateMultiFrameResource(FTextureRHIParamRef Texture) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHIEndUpdateMultiFrameResource)(Texture); return; } new (AllocCommand<FRHICommandEndUpdateMultiFrameResource>()) FRHICommandEndUpdateMultiFrameResource(Texture); } FORCEINLINE_DEBUGGABLE void BeginUpdateMultiFrameResource(FUnorderedAccessViewRHIParamRef UAV) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHIBeginUpdateMultiFrameResource)(UAV); return; } new (AllocCommand<FRHICommandBeginUpdateMultiFrameUAV>()) FRHICommandBeginUpdateMultiFrameUAV(UAV); } FORCEINLINE_DEBUGGABLE void EndUpdateMultiFrameResource(FUnorderedAccessViewRHIParamRef UAV) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHIEndUpdateMultiFrameResource)(UAV); return; } new (AllocCommand<FRHICommandEndUpdateMultiFrameUAV>()) FRHICommandEndUpdateMultiFrameUAV(UAV); } FORCEINLINE_DEBUGGABLE FLocalGraphicsPipelineState BuildLocalGraphicsPipelineState( const FGraphicsPipelineStateInitializer& Initializer ) { check(IsOutsideRenderPass()); FLocalGraphicsPipelineState Result; if (Bypass()) { Result.BypassGraphicsPipelineState = RHICreateGraphicsPipelineState(Initializer); } else { auto* Cmd = new (AllocCommand<FRHICommandBuildLocalGraphicsPipelineState>()) FRHICommandBuildLocalGraphicsPipelineState(this, Initializer); Result.WorkArea = &Cmd->WorkArea; } return Result; } FORCEINLINE_DEBUGGABLE void SetLocalGraphicsPipelineState(FLocalGraphicsPipelineState LocalGraphicsPipelineState) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHISetGraphicsPipelineState)(LocalGraphicsPipelineState.BypassGraphicsPipelineState); return; } new (AllocCommand<FRHICommandSetLocalGraphicsPipelineState>()) FRHICommandSetLocalGraphicsPipelineState(this, LocalGraphicsPipelineState); } FORCEINLINE_DEBUGGABLE FLocalUniformBuffer BuildLocalUniformBuffer(const void* Contents, uint32 ContentsSize, const FRHIUniformBufferLayout& Layout) { check(IsOutsideRenderPass()); FLocalUniformBuffer Result; if (Bypass()) { Result.BypassUniform = RHICreateUniformBuffer(Contents, Layout, UniformBuffer_SingleFrame); } else { check(Contents && ContentsSize && (&Layout != nullptr)); auto* Cmd = new (AllocCommand<FRHICommandBuildLocalUniformBuffer>()) FRHICommandBuildLocalUniformBuffer(this, Contents, ContentsSize, Layout); Result.WorkArea = &Cmd->WorkArea; } return Result; } template <typename TShaderRHIParamRef> FORCEINLINE_DEBUGGABLE void SetLocalShaderUniformBuffer(TShaderRHIParamRef Shader, uint32 BaseIndex, const FLocalUniformBuffer& UniformBuffer) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHISetShaderUniformBuffer)(Shader, BaseIndex, UniformBuffer.BypassUniform); return; } new (AllocCommand<FRHICommandSetLocalUniformBuffer<TShaderRHIParamRef> >()) FRHICommandSetLocalUniformBuffer<TShaderRHIParamRef>(this, Shader, BaseIndex, UniformBuffer); } template <typename TShaderRHI> FORCEINLINE_DEBUGGABLE void SetLocalShaderUniformBuffer(TRefCountPtr<TShaderRHI>& Shader, uint32 BaseIndex, const FLocalUniformBuffer& UniformBuffer) { SetLocalShaderUniformBuffer(Shader.GetReference(), BaseIndex, UniformBuffer); } template <typename TShaderRHI> FORCEINLINE_DEBUGGABLE void SetShaderUniformBuffer(TShaderRHI* Shader, uint32 BaseIndex, FUniformBufferRHIParamRef UniformBuffer) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHISetShaderUniformBuffer)(Shader, BaseIndex, UniformBuffer); return; } new (AllocCommand<FRHICommandSetShaderUniformBuffer<TShaderRHI*, ECmdList::EGfx> >()) FRHICommandSetShaderUniformBuffer<TShaderRHI*, ECmdList::EGfx>(Shader, BaseIndex, UniformBuffer); } template <typename TShaderRHI> FORCEINLINE void SetShaderUniformBuffer(TRefCountPtr<TShaderRHI>& Shader, uint32 BaseIndex, FUniformBufferRHIParamRef UniformBuffer) { SetShaderUniformBuffer(Shader.GetReference(), BaseIndex, UniformBuffer); } template <typename TShaderRHI> FORCEINLINE_DEBUGGABLE void SetShaderParameter(TShaderRHI* Shader, uint32 BufferIndex, uint32 BaseIndex, uint32 NumBytes, const void* NewValue) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHISetShaderParameter)(Shader, BufferIndex, BaseIndex, NumBytes, NewValue); return; } void* UseValue = Alloc(NumBytes, 16); FMemory::Memcpy(UseValue, NewValue, NumBytes); new (AllocCommand<FRHICommandSetShaderParameter<TShaderRHI*, ECmdList::EGfx> >()) FRHICommandSetShaderParameter<TShaderRHI*, ECmdList::EGfx>(Shader, BufferIndex, BaseIndex, NumBytes, UseValue); } template <typename TShaderRHI> FORCEINLINE void SetShaderParameter(TRefCountPtr<TShaderRHI>& Shader, uint32 BufferIndex, uint32 BaseIndex, uint32 NumBytes, const void* NewValue) { SetShaderParameter(Shader.GetReference(), BufferIndex, BaseIndex, NumBytes, NewValue); } template <typename TShaderRHIParamRef> FORCEINLINE_DEBUGGABLE void SetShaderTexture(TShaderRHIParamRef Shader, uint32 TextureIndex, FTextureRHIParamRef Texture) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHISetShaderTexture)(Shader, TextureIndex, Texture); return; } new (AllocCommand<FRHICommandSetShaderTexture<TShaderRHIParamRef, ECmdList::EGfx> >()) FRHICommandSetShaderTexture<TShaderRHIParamRef, ECmdList::EGfx>(Shader, TextureIndex, Texture); } template <typename TShaderRHI> FORCEINLINE_DEBUGGABLE void SetShaderTexture(TRefCountPtr<TShaderRHI>& Shader, uint32 TextureIndex, FTextureRHIParamRef Texture) { SetShaderTexture(Shader.GetReference(), TextureIndex, Texture); } template <typename TShaderRHIParamRef> FORCEINLINE_DEBUGGABLE void SetShaderResourceViewParameter(TShaderRHIParamRef Shader, uint32 SamplerIndex, FShaderResourceViewRHIParamRef SRV) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHISetShaderResourceViewParameter)(Shader, SamplerIndex, SRV); return; } new (AllocCommand<FRHICommandSetShaderResourceViewParameter<TShaderRHIParamRef, ECmdList::EGfx> >()) FRHICommandSetShaderResourceViewParameter<TShaderRHIParamRef, ECmdList::EGfx>(Shader, SamplerIndex, SRV); } template <typename TShaderRHI> FORCEINLINE_DEBUGGABLE void SetShaderResourceViewParameter(TRefCountPtr<TShaderRHI>& Shader, uint32 SamplerIndex, FShaderResourceViewRHIParamRef SRV) { SetShaderResourceViewParameter(Shader.GetReference(), SamplerIndex, SRV); } template <typename TShaderRHIParamRef> FORCEINLINE_DEBUGGABLE void SetShaderSampler(TShaderRHIParamRef Shader, uint32 SamplerIndex, FSamplerStateRHIParamRef State) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHISetShaderSampler)(Shader, SamplerIndex, State); return; } new (AllocCommand<FRHICommandSetShaderSampler<TShaderRHIParamRef, ECmdList::EGfx> >()) FRHICommandSetShaderSampler<TShaderRHIParamRef, ECmdList::EGfx>(Shader, SamplerIndex, State); } template <typename TShaderRHI> FORCEINLINE_DEBUGGABLE void SetShaderSampler(TRefCountPtr<TShaderRHI>& Shader, uint32 SamplerIndex, FSamplerStateRHIParamRef State) { SetShaderSampler(Shader.GetReference(), SamplerIndex, State); } FORCEINLINE_DEBUGGABLE void SetUAVParameter(FComputeShaderRHIParamRef Shader, uint32 UAVIndex, FUnorderedAccessViewRHIParamRef UAV) { if (Bypass()) { CMD_CONTEXT(RHISetUAVParameter)(Shader, UAVIndex, UAV); return; } new (AllocCommand<FRHICommandSetUAVParameter<FComputeShaderRHIParamRef, ECmdList::EGfx> >()) FRHICommandSetUAVParameter<FComputeShaderRHIParamRef, ECmdList::EGfx>(Shader, UAVIndex, UAV); } FORCEINLINE_DEBUGGABLE void SetUAVParameter(TRefCountPtr<FRHIComputeShader>& Shader, uint32 UAVIndex, FUnorderedAccessViewRHIParamRef UAV) { SetUAVParameter(Shader.GetReference(), UAVIndex, UAV); } FORCEINLINE_DEBUGGABLE void SetUAVParameter(FComputeShaderRHIParamRef Shader, uint32 UAVIndex, FUnorderedAccessViewRHIParamRef UAV, uint32 InitialCount) { if (Bypass()) { CMD_CONTEXT(RHISetUAVParameter)(Shader, UAVIndex, UAV, InitialCount); return; } new (AllocCommand<FRHICommandSetUAVParameter_IntialCount<FComputeShaderRHIParamRef, ECmdList::EGfx> >()) FRHICommandSetUAVParameter_IntialCount<FComputeShaderRHIParamRef, ECmdList::EGfx>(Shader, UAVIndex, UAV, InitialCount); } FORCEINLINE_DEBUGGABLE void SetUAVParameter(TRefCountPtr<FRHIComputeShader>& Shader, uint32 UAVIndex, FUnorderedAccessViewRHIParamRef UAV, uint32 InitialCount) { SetUAVParameter(Shader.GetReference(), UAVIndex, UAV, InitialCount); } FORCEINLINE_DEBUGGABLE void SetBlendFactor(const FLinearColor& BlendFactor = FLinearColor::White) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHISetBlendFactor)(BlendFactor); return; } new (AllocCommand<FRHICommandSetBlendFactor>()) FRHICommandSetBlendFactor(BlendFactor); } // WaveWorks Start FORCEINLINE_DEBUGGABLE void SetWaveWorksState(FWaveWorksRHIParamRef State, const FMatrix ViewMatrix, const TArray<uint32>& ShaderInputMappings) { if (Bypass()) { CMD_CONTEXT(RHISetWaveWorksState)(State, ViewMatrix, ShaderInputMappings); return; } new (AllocCommand<FRHICommandSetWaveWorksState>()) FRHICommandSetWaveWorksState(State, ViewMatrix, ShaderInputMappings); } // WaveWorks End FORCEINLINE_DEBUGGABLE void DrawPrimitive(uint32 PrimitiveType, uint32 BaseVertexIndex, uint32 NumPrimitives, uint32 NumInstances) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHIDrawPrimitive)(PrimitiveType, BaseVertexIndex, NumPrimitives, NumInstances); return; } new (AllocCommand<FRHICommandDrawPrimitive>()) FRHICommandDrawPrimitive(PrimitiveType, BaseVertexIndex, NumPrimitives, NumInstances); } FORCEINLINE_DEBUGGABLE void DrawIndexedPrimitive(FIndexBufferRHIParamRef IndexBuffer, uint32 PrimitiveType, int32 BaseVertexIndex, uint32 FirstInstance, uint32 NumVertices, uint32 StartIndex, uint32 NumPrimitives, uint32 NumInstances) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHIDrawIndexedPrimitive)(IndexBuffer, PrimitiveType, BaseVertexIndex, FirstInstance, NumVertices, StartIndex, NumPrimitives, NumInstances); return; } new (AllocCommand<FRHICommandDrawIndexedPrimitive>()) FRHICommandDrawIndexedPrimitive(IndexBuffer, PrimitiveType, BaseVertexIndex, FirstInstance, NumVertices, StartIndex, NumPrimitives, NumInstances); } PRAGMA_DISABLE_DEPRECATION_WARNINGS DEPRECATED(4.18, "Use alternate SetStreamSource() call with no Stride parameter.") FORCEINLINE_DEBUGGABLE void SetStreamSource(uint32 StreamIndex, FVertexBufferRHIParamRef VertexBuffer, uint32 Stride, uint32 Offset) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHISetStreamSource)(StreamIndex, VertexBuffer, Stride, Offset); return; } new (AllocCommand<FRHICommandSetStreamSource>()) FRHICommandSetStreamSourceDEPRECATED(StreamIndex, VertexBuffer, Stride, Offset); } PRAGMA_ENABLE_DEPRECATION_WARNINGS FORCEINLINE_DEBUGGABLE void SetStreamSource(uint32 StreamIndex, FVertexBufferRHIParamRef VertexBuffer, uint32 Offset) { if (Bypass()) { CMD_CONTEXT(RHISetStreamSource)(StreamIndex, VertexBuffer, Offset); return; } new (AllocCommand<FRHICommandSetStreamSource>()) FRHICommandSetStreamSource(StreamIndex, VertexBuffer, Offset); } FORCEINLINE_DEBUGGABLE void SetStencilRef(uint32 StencilRef) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHISetStencilRef)(StencilRef); return; } new(AllocCommand<FRHICommandSetStencilRef>()) FRHICommandSetStencilRef(StencilRef); } FORCEINLINE_DEBUGGABLE void SetViewport(uint32 MinX, uint32 MinY, float MinZ, uint32 MaxX, uint32 MaxY, float MaxZ) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHISetViewport)(MinX, MinY, MinZ, MaxX, MaxY, MaxZ); return; } new (AllocCommand<FRHICommandSetViewport>()) FRHICommandSetViewport(MinX, MinY, MinZ, MaxX, MaxY, MaxZ); } FORCEINLINE_DEBUGGABLE void SetStereoViewport(uint32 LeftMinX, uint32 RightMinX, uint32 LeftMinY, uint32 RightMinY, float MinZ, uint32 LeftMaxX, uint32 RightMaxX, uint32 LeftMaxY, uint32 RightMaxY, float MaxZ) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHISetStereoViewport)(LeftMinX, RightMinX, LeftMinY, RightMinY, MinZ, LeftMaxX, RightMaxX, LeftMaxY, RightMaxY, MaxZ); return; } new (AllocCommand<FRHICommandSetStereoViewport>()) FRHICommandSetStereoViewport(LeftMinX, RightMinX, LeftMinY, RightMinY, MinZ, LeftMaxX, RightMaxX, LeftMaxY, RightMaxY, MaxZ); } FORCEINLINE_DEBUGGABLE void SetScissorRect(bool bEnable, uint32 MinX, uint32 MinY, uint32 MaxX, uint32 MaxY) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHISetScissorRect)(bEnable, MinX, MinY, MaxX, MaxY); return; } new (AllocCommand<FRHICommandSetScissorRect>()) FRHICommandSetScissorRect(bEnable, MinX, MinY, MaxX, MaxY); } void ApplyCachedRenderTargets( FGraphicsPipelineStateInitializer& GraphicsPSOInit ) { GraphicsPSOInit.RenderTargetsEnabled = PSOContext.CachedNumSimultanousRenderTargets; for (uint32 i = 0; i < GraphicsPSOInit.RenderTargetsEnabled; ++i) { if (PSOContext.CachedRenderTargets[i].Texture) { GraphicsPSOInit.RenderTargetFormats[i] = PSOContext.CachedRenderTargets[i].Texture->GetFormat(); GraphicsPSOInit.RenderTargetFlags[i] = PSOContext.CachedRenderTargets[i].Texture->GetFlags(); } else { GraphicsPSOInit.RenderTargetFormats[i] = PF_Unknown; } GraphicsPSOInit.RenderTargetLoadActions[i] = PSOContext.CachedRenderTargets[i].LoadAction; GraphicsPSOInit.RenderTargetStoreActions[i] = PSOContext.CachedRenderTargets[i].StoreAction; if (GraphicsPSOInit.RenderTargetFormats[i] != PF_Unknown) { GraphicsPSOInit.NumSamples = PSOContext.CachedRenderTargets[i].Texture->GetNumSamples(); } } if (PSOContext.CachedDepthStencilTarget.Texture) { GraphicsPSOInit.DepthStencilTargetFormat = PSOContext.CachedDepthStencilTarget.Texture->GetFormat(); GraphicsPSOInit.DepthStencilTargetFlag = PSOContext.CachedDepthStencilTarget.Texture->GetFlags(); } else { GraphicsPSOInit.DepthStencilTargetFormat = PF_Unknown; } GraphicsPSOInit.DepthTargetLoadAction = PSOContext.CachedDepthStencilTarget.DepthLoadAction; GraphicsPSOInit.DepthTargetStoreAction = PSOContext.CachedDepthStencilTarget.DepthStoreAction; GraphicsPSOInit.StencilTargetLoadAction = PSOContext.CachedDepthStencilTarget.StencilLoadAction; GraphicsPSOInit.StencilTargetStoreAction = PSOContext.CachedDepthStencilTarget.GetStencilStoreAction(); if (GraphicsPSOInit.DepthStencilTargetFormat != PF_Unknown) { GraphicsPSOInit.NumSamples = PSOContext.CachedDepthStencilTarget.Texture->GetNumSamples(); } } FORCEINLINE_DEBUGGABLE void SetRenderTargets( uint32 NewNumSimultaneousRenderTargets, const FRHIRenderTargetView* NewRenderTargetsRHI, const FRHIDepthRenderTargetView* NewDepthStencilTargetRHI, uint32 NewNumUAVs, const FUnorderedAccessViewRHIParamRef* UAVs ) { check(IsOutsideRenderPass()); CacheActiveRenderTargets( NewNumSimultaneousRenderTargets, NewRenderTargetsRHI, NewDepthStencilTargetRHI ); if (Bypass()) { CMD_CONTEXT(RHISetRenderTargets)( NewNumSimultaneousRenderTargets, NewRenderTargetsRHI, NewDepthStencilTargetRHI, NewNumUAVs, UAVs); return; } new (AllocCommand<FRHICommandSetRenderTargets>()) FRHICommandSetRenderTargets( NewNumSimultaneousRenderTargets, NewRenderTargetsRHI, NewDepthStencilTargetRHI, NewNumUAVs, UAVs); } FORCEINLINE_DEBUGGABLE void SetRenderTargetsAndClear(const FRHISetRenderTargetsInfo& RenderTargetsInfo) { check(IsOutsideRenderPass()); CacheActiveRenderTargets( RenderTargetsInfo.NumColorRenderTargets, RenderTargetsInfo.ColorRenderTarget, &RenderTargetsInfo.DepthStencilRenderTarget ); if (Bypass()) { CMD_CONTEXT(RHISetRenderTargetsAndClear)(RenderTargetsInfo); return; } new (AllocCommand<FRHICommandSetRenderTargetsAndClear>()) FRHICommandSetRenderTargetsAndClear(RenderTargetsInfo); } FORCEINLINE_DEBUGGABLE void BindClearMRTValues(bool bClearColor, bool bClearDepth, bool bClearStencil) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHIBindClearMRTValues)(bClearColor, bClearDepth, bClearStencil); return; } new (AllocCommand<FRHICommandBindClearMRTValues>()) FRHICommandBindClearMRTValues(bClearColor, bClearDepth, bClearStencil); } FORCEINLINE_DEBUGGABLE void BeginDrawPrimitiveUP(uint32 PrimitiveType, uint32 NumPrimitives, uint32 NumVertices, uint32 VertexDataStride, void*& OutVertexData) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHIBeginDrawPrimitiveUP)(PrimitiveType, NumPrimitives, NumVertices, VertexDataStride, OutVertexData); return; } check(!DrawUPData.OutVertexData && NumVertices * VertexDataStride > 0); OutVertexData = Alloc(NumVertices * VertexDataStride, 16); DrawUPData.PrimitiveType = PrimitiveType; DrawUPData.NumPrimitives = NumPrimitives; DrawUPData.NumVertices = NumVertices; DrawUPData.VertexDataStride = VertexDataStride; DrawUPData.OutVertexData = OutVertexData; } FORCEINLINE_DEBUGGABLE void EndDrawPrimitiveUP() { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHIEndDrawPrimitiveUP)(); return; } check(DrawUPData.OutVertexData && DrawUPData.NumVertices); new (AllocCommand<FRHICommandEndDrawPrimitiveUP>()) FRHICommandEndDrawPrimitiveUP(DrawUPData.PrimitiveType, DrawUPData.NumPrimitives, DrawUPData.NumVertices, DrawUPData.VertexDataStride, DrawUPData.OutVertexData); DrawUPData.OutVertexData = nullptr; DrawUPData.NumVertices = 0; } FORCEINLINE_DEBUGGABLE void BeginDrawIndexedPrimitiveUP(uint32 PrimitiveType, uint32 NumPrimitives, uint32 NumVertices, uint32 VertexDataStride, void*& OutVertexData, uint32 MinVertexIndex, uint32 NumIndices, uint32 IndexDataStride, void*& OutIndexData) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHIBeginDrawIndexedPrimitiveUP)(PrimitiveType, NumPrimitives, NumVertices, VertexDataStride, OutVertexData, MinVertexIndex, NumIndices, IndexDataStride, OutIndexData); return; } check(!DrawUPData.OutVertexData && !DrawUPData.OutIndexData && NumVertices * VertexDataStride > 0 && NumIndices * IndexDataStride > 0); OutVertexData = Alloc(NumVertices * VertexDataStride, 16); OutIndexData = Alloc(NumIndices * IndexDataStride, 16); DrawUPData.PrimitiveType = PrimitiveType; DrawUPData.NumPrimitives = NumPrimitives; DrawUPData.NumVertices = NumVertices; DrawUPData.VertexDataStride = VertexDataStride; DrawUPData.OutVertexData = OutVertexData; DrawUPData.MinVertexIndex = MinVertexIndex; DrawUPData.NumIndices = NumIndices; DrawUPData.IndexDataStride = IndexDataStride; DrawUPData.OutIndexData = OutIndexData; } FORCEINLINE_DEBUGGABLE void EndDrawIndexedPrimitiveUP() { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHIEndDrawIndexedPrimitiveUP)(); return; } check(DrawUPData.OutVertexData && DrawUPData.OutIndexData && DrawUPData.NumIndices && DrawUPData.NumVertices); new (AllocCommand<FRHICommandEndDrawIndexedPrimitiveUP>()) FRHICommandEndDrawIndexedPrimitiveUP(DrawUPData.PrimitiveType, DrawUPData.NumPrimitives, DrawUPData.NumVertices, DrawUPData.VertexDataStride, DrawUPData.OutVertexData, DrawUPData.MinVertexIndex, DrawUPData.NumIndices, DrawUPData.IndexDataStride, DrawUPData.OutIndexData); DrawUPData.OutVertexData = nullptr; DrawUPData.OutIndexData = nullptr; DrawUPData.NumIndices = 0; DrawUPData.NumVertices = 0; } FORCEINLINE_DEBUGGABLE void SetComputeShader(FComputeShaderRHIParamRef ComputeShader) { if (Bypass()) { CMD_CONTEXT(RHISetComputeShader)(ComputeShader); return; } new (AllocCommand<FRHICommandSetComputeShader<ECmdList::EGfx>>()) FRHICommandSetComputeShader<ECmdList::EGfx>(ComputeShader); } FORCEINLINE_DEBUGGABLE void SetComputePipelineState(class FComputePipelineState* ComputePipelineState) { if (Bypass()) { extern RHI_API FRHIComputePipelineState* ExecuteSetComputePipelineState(class FComputePipelineState* ComputePipelineState); FRHIComputePipelineState* RHIComputePipelineState = ExecuteSetComputePipelineState(ComputePipelineState); CMD_CONTEXT(RHISetComputePipelineState)(RHIComputePipelineState); return; } new (AllocCommand<FRHICommandSetComputePipelineState<ECmdList::EGfx>>()) FRHICommandSetComputePipelineState<ECmdList::EGfx>(ComputePipelineState); } FORCEINLINE_DEBUGGABLE void SetGraphicsPipelineState(class FGraphicsPipelineState* GraphicsPipelineState) { check(IsOutsideRenderPass()); if (Bypass()) { extern RHI_API FRHIGraphicsPipelineState* ExecuteSetGraphicsPipelineState(class FGraphicsPipelineState* GraphicsPipelineState); FRHIGraphicsPipelineState* RHIGraphicsPipelineState = ExecuteSetGraphicsPipelineState(GraphicsPipelineState); CMD_CONTEXT(RHISetGraphicsPipelineState)(RHIGraphicsPipelineState); return; } new (AllocCommand<FRHICommandSetGraphicsPipelineState>()) FRHICommandSetGraphicsPipelineState(GraphicsPipelineState); } FORCEINLINE_DEBUGGABLE void DispatchComputeShader(uint32 ThreadGroupCountX, uint32 ThreadGroupCountY, uint32 ThreadGroupCountZ) { if (Bypass()) { CMD_CONTEXT(RHIDispatchComputeShader)(ThreadGroupCountX, ThreadGroupCountY, ThreadGroupCountZ); return; } new (AllocCommand<FRHICommandDispatchComputeShader<ECmdList::EGfx>>()) FRHICommandDispatchComputeShader<ECmdList::EGfx>(ThreadGroupCountX, ThreadGroupCountY, ThreadGroupCountZ); } FORCEINLINE_DEBUGGABLE void DispatchIndirectComputeShader(FVertexBufferRHIParamRef ArgumentBuffer, uint32 ArgumentOffset) { if (Bypass()) { CMD_CONTEXT(RHIDispatchIndirectComputeShader)(ArgumentBuffer, ArgumentOffset); return; } new (AllocCommand<FRHICommandDispatchIndirectComputeShader<ECmdList::EGfx>>()) FRHICommandDispatchIndirectComputeShader<ECmdList::EGfx>(ArgumentBuffer, ArgumentOffset); } FORCEINLINE_DEBUGGABLE void AutomaticCacheFlushAfterComputeShader(bool bEnable) { if (Bypass()) { CMD_CONTEXT(RHIAutomaticCacheFlushAfterComputeShader)(bEnable); return; } new (AllocCommand<FRHICommandAutomaticCacheFlushAfterComputeShader>()) FRHICommandAutomaticCacheFlushAfterComputeShader(bEnable); } FORCEINLINE_DEBUGGABLE void FlushComputeShaderCache() { if (Bypass()) { CMD_CONTEXT(RHIFlushComputeShaderCache)(); return; } new (AllocCommand<FRHICommandFlushComputeShaderCache>()) FRHICommandFlushComputeShaderCache(); } FORCEINLINE_DEBUGGABLE void DrawPrimitiveIndirect(uint32 PrimitiveType, FVertexBufferRHIParamRef ArgumentBuffer, uint32 ArgumentOffset) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHIDrawPrimitiveIndirect)(PrimitiveType, ArgumentBuffer, ArgumentOffset); return; } new (AllocCommand<FRHICommandDrawPrimitiveIndirect>()) FRHICommandDrawPrimitiveIndirect(PrimitiveType, ArgumentBuffer, ArgumentOffset); } FORCEINLINE_DEBUGGABLE void DrawIndexedIndirect(FIndexBufferRHIParamRef IndexBufferRHI, uint32 PrimitiveType, FStructuredBufferRHIParamRef ArgumentsBufferRHI, uint32 DrawArgumentsIndex, uint32 NumInstances) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHIDrawIndexedIndirect)(IndexBufferRHI, PrimitiveType, ArgumentsBufferRHI, DrawArgumentsIndex, NumInstances); return; } new (AllocCommand<FRHICommandDrawIndexedIndirect>()) FRHICommandDrawIndexedIndirect(IndexBufferRHI, PrimitiveType, ArgumentsBufferRHI, DrawArgumentsIndex, NumInstances); } FORCEINLINE_DEBUGGABLE void DrawIndexedPrimitiveIndirect(uint32 PrimitiveType, FIndexBufferRHIParamRef IndexBuffer, FVertexBufferRHIParamRef ArgumentsBuffer, uint32 ArgumentOffset) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHIDrawIndexedPrimitiveIndirect)(PrimitiveType, IndexBuffer, ArgumentsBuffer, ArgumentOffset); return; } new (AllocCommand<FRHICommandDrawIndexedPrimitiveIndirect>()) FRHICommandDrawIndexedPrimitiveIndirect(PrimitiveType, IndexBuffer, ArgumentsBuffer, ArgumentOffset); } FORCEINLINE_DEBUGGABLE void EnableDepthBoundsTest(bool bEnable, float MinDepth, float MaxDepth) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHIEnableDepthBoundsTest)(bEnable, MinDepth, MaxDepth); return; } new (AllocCommand<FRHICommandEnableDepthBoundsTest>()) FRHICommandEnableDepthBoundsTest(bEnable, MinDepth, MaxDepth); } FORCEINLINE_DEBUGGABLE void CopyToResolveTarget(FTextureRHIParamRef SourceTextureRHI, FTextureRHIParamRef DestTextureRHI, bool bKeepOriginalSurface, const FResolveParams& ResolveParams) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHICopyToResolveTarget)(SourceTextureRHI, DestTextureRHI, bKeepOriginalSurface, ResolveParams); return; } new (AllocCommand<FRHICommandCopyToResolveTarget>()) FRHICommandCopyToResolveTarget(SourceTextureRHI, DestTextureRHI, bKeepOriginalSurface, ResolveParams); } FORCEINLINE_DEBUGGABLE void CopyTexture(FTextureRHIParamRef SourceTextureRHI, FTextureRHIParamRef DestTextureRHI, const FResolveParams& ResolveParams) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHICopyTexture)(SourceTextureRHI, DestTextureRHI, ResolveParams); return; } new (AllocCommand<FRHICommandCopyTexture>()) FRHICommandCopyTexture(SourceTextureRHI, DestTextureRHI, ResolveParams); } FORCEINLINE_DEBUGGABLE void ClearTinyUAV(FUnorderedAccessViewRHIParamRef UnorderedAccessViewRHI, const uint32(&Values)[4]) { check(IsOutsideRenderPass()); if (Bypass()) { CMD_CONTEXT(RHIClearTinyUAV)(UnorderedAccessViewRHI, Values); return; } new (AllocCommand<FRHICommandClearTinyUAV>()) FRHICommandClearTinyUAV(UnorderedAccessViewRHI, Values); } // NVCHANGE_BEGIN: Add HBAO+ #if WITH_GFSDK_SSAO FORCEINLINE_DEBUGGABLE void RenderHBAO( const FTextureRHIParamRef SceneDepthTextureRHI, const FMatrix& ProjectionMatrix, const FTextureRHIParamRef SceneNormalTextureRHI, const FMatrix& ViewMatrix, const FTextureRHIParamRef SceneColorTextureRHI, const GFSDK_SSAO_Parameters& AOParams ) { if (Bypass()) { CMD_CONTEXT(RHIRenderHBAO)( SceneDepthTextureRHI, ProjectionMatrix, SceneNormalTextureRHI, ViewMatrix, SceneColorTextureRHI, AOParams); return; } new (AllocCommand<FRHICommandRenderHBAO>()) FRHICommandRenderHBAO( SceneDepthTextureRHI, ProjectionMatrix, SceneNormalTextureRHI, ViewMatrix, SceneColorTextureRHI, AOParams); } #endif // NVCHANGE_END: Add HBAO+ FORCEINLINE_DEBUGGABLE void BeginRenderQuery(FRenderQueryRHIParamRef RenderQuery) { if (Bypass()) { CMD_CONTEXT(RHIBeginRenderQuery)(RenderQuery); return; } new (AllocCommand<FRHICommandBeginRenderQuery>()) FRHICommandBeginRenderQuery(RenderQuery); } FORCEINLINE_DEBUGGABLE void EndRenderQuery(FRenderQueryRHIParamRef RenderQuery) { if (Bypass()) { CMD_CONTEXT(RHIEndRenderQuery)(RenderQuery); return; } new (AllocCommand<FRHICommandEndRenderQuery>()) FRHICommandEndRenderQuery(RenderQuery); } FORCEINLINE_DEBUGGABLE void BeginOcclusionQueryBatch() { if (Bypass()) { CMD_CONTEXT(RHIBeginOcclusionQueryBatch)(); return; } new (AllocCommand<FRHICommandBeginOcclusionQueryBatch>()) FRHICommandBeginOcclusionQueryBatch(); } FORCEINLINE_DEBUGGABLE void EndOcclusionQueryBatch() { if (Bypass()) { CMD_CONTEXT(RHIEndOcclusionQueryBatch)(); return; } new (AllocCommand<FRHICommandEndOcclusionQueryBatch>()) FRHICommandEndOcclusionQueryBatch(); } FORCEINLINE_DEBUGGABLE void SubmitCommandsHint() { if (Bypass()) { CMD_CONTEXT(RHISubmitCommandsHint)(); return; } new (AllocCommand<FRHICommandSubmitCommandsHint<ECmdList::EGfx>>()) FRHICommandSubmitCommandsHint<ECmdList::EGfx>(); } FORCEINLINE_DEBUGGABLE void TransitionResource(EResourceTransitionAccess TransitionType, FTextureRHIParamRef InTexture) { FTextureRHIParamRef Texture = InTexture; check(Texture == nullptr || Texture->IsCommitted()); if (Bypass()) { CMD_CONTEXT(RHITransitionResources)(TransitionType, &Texture, 1); return; } // Allocate space to hold the single texture pointer inline in the command list itself. FTextureRHIParamRef* TextureArray = (FTextureRHIParamRef*)Alloc(sizeof(FTextureRHIParamRef), alignof(FTextureRHIParamRef)); TextureArray[0] = Texture; new (AllocCommand<FRHICommandTransitionTextures>()) FRHICommandTransitionTextures(TransitionType, TextureArray, 1); } FORCEINLINE_DEBUGGABLE void TransitionResources(EResourceTransitionAccess TransitionType, FTextureRHIParamRef* InTextures, int32 NumTextures) { if (Bypass()) { CMD_CONTEXT(RHITransitionResources)(TransitionType, InTextures, NumTextures); return; } // Allocate space to hold the list of textures inline in the command list itself. FTextureRHIParamRef* InlineTextureArray = (FTextureRHIParamRef*)Alloc(sizeof(FTextureRHIParamRef) * NumTextures, alignof(FTextureRHIParamRef)); for (int32 Index = 0; Index < NumTextures; ++Index) { InlineTextureArray[Index] = InTextures[Index]; } new (AllocCommand<FRHICommandTransitionTextures>()) FRHICommandTransitionTextures(TransitionType, InlineTextureArray, NumTextures); } FORCEINLINE_DEBUGGABLE void TransitionResourceArrayNoCopy(EResourceTransitionAccess TransitionType, TArray<FTextureRHIParamRef>& InTextures) { if (Bypass()) { CMD_CONTEXT(RHITransitionResources)(TransitionType, &InTextures[0], InTextures.Num()); return; } new (AllocCommand<FRHICommandTransitionTexturesArray>()) FRHICommandTransitionTexturesArray(TransitionType, InTextures); } FORCEINLINE_DEBUGGABLE void TransitionResource(EResourceTransitionAccess TransitionType, EResourceTransitionPipeline TransitionPipeline, FUnorderedAccessViewRHIParamRef InUAV, FComputeFenceRHIParamRef WriteFence) { FUnorderedAccessViewRHIParamRef UAV = InUAV; check(InUAV == nullptr || InUAV->IsCommitted()); if (Bypass()) { CMD_CONTEXT(RHITransitionResources)(TransitionType, TransitionPipeline, &UAV, 1, WriteFence); return; } // Allocate space to hold the single UAV pointer inline in the command list itself. FUnorderedAccessViewRHIParamRef* UAVArray = (FUnorderedAccessViewRHIParamRef*)Alloc(sizeof(FUnorderedAccessViewRHIParamRef), alignof(FUnorderedAccessViewRHIParamRef)); UAVArray[0] = UAV; new (AllocCommand<FRHICommandTransitionUAVs<ECmdList::EGfx>>()) FRHICommandTransitionUAVs<ECmdList::EGfx>(TransitionType, TransitionPipeline, UAVArray, 1, WriteFence); } FORCEINLINE_DEBUGGABLE void TransitionResource(EResourceTransitionAccess TransitionType, EResourceTransitionPipeline TransitionPipeline, FUnorderedAccessViewRHIParamRef InUAV) { check(InUAV == nullptr || InUAV->IsCommitted()); TransitionResource(TransitionType, TransitionPipeline, InUAV, nullptr); } FORCEINLINE_DEBUGGABLE void TransitionResources(EResourceTransitionAccess TransitionType, EResourceTransitionPipeline TransitionPipeline, FUnorderedAccessViewRHIParamRef* InUAVs, int32 NumUAVs, FComputeFenceRHIParamRef WriteFence) { if (Bypass()) { CMD_CONTEXT(RHITransitionResources)(TransitionType, TransitionPipeline, InUAVs, NumUAVs, WriteFence); return; } // Allocate space to hold the list UAV pointers inline in the command list itself. FUnorderedAccessViewRHIParamRef* UAVArray = (FUnorderedAccessViewRHIParamRef*)Alloc(sizeof(FUnorderedAccessViewRHIParamRef) * NumUAVs, alignof(FUnorderedAccessViewRHIParamRef)); for (int32 Index = 0; Index < NumUAVs; ++Index) { UAVArray[Index] = InUAVs[Index]; } new (AllocCommand<FRHICommandTransitionUAVs<ECmdList::EGfx>>()) FRHICommandTransitionUAVs<ECmdList::EGfx>(TransitionType, TransitionPipeline, UAVArray, NumUAVs, WriteFence); } FORCEINLINE_DEBUGGABLE void TransitionResources(EResourceTransitionAccess TransitionType, EResourceTransitionPipeline TransitionPipeline, FUnorderedAccessViewRHIParamRef* InUAVs, int32 NumUAVs) { TransitionResources(TransitionType, TransitionPipeline, InUAVs, NumUAVs, nullptr); } FORCEINLINE_DEBUGGABLE void WaitComputeFence(FComputeFenceRHIParamRef WaitFence) { if (Bypass()) { CMD_CONTEXT(RHIWaitComputeFence)(WaitFence); return; } new (AllocCommand<FRHICommandWaitComputeFence<ECmdList::EGfx>>()) FRHICommandWaitComputeFence<ECmdList::EGfx>(WaitFence); } FRHIRenderPassCommandList& BeginRenderPass(const FRHIRenderPassInfo& InInfo, const TCHAR* Name) { check(IsOutsideRenderPass()); FRHIRenderPassCommandList& RenderPassCmdList = *(FRHIRenderPassCommandList*)this; Data.LocalRHIRenderPass = new(Alloc<FLocalCmdListRenderPass>()) FLocalCmdListRenderPass; CacheActiveRenderTargets(InInfo); if (Bypass()) { check(!Data.LocalRHIRenderPass->RenderPass.GetReference()); Data.LocalRHIRenderPass->RenderPass = CMD_CONTEXT(RHIBeginRenderPass)(InInfo, Name); } else { TCHAR* NameCopy = AllocString(Name); new (AllocCommand<FRHICommandBeginRenderPass>()) FRHICommandBeginRenderPass(InInfo, Data.LocalRHIRenderPass, NameCopy); } return RenderPassCmdList; } void EndRenderPass(FRHIRenderPassCommandList& RenderPass) { check(Data.LocalRHIRenderPass); if (Bypass()) { CMD_CONTEXT(RHIEndRenderPass)(Data.LocalRHIRenderPass->RenderPass); } else { new (AllocCommand<FRHICommandEndRenderPass>()) FRHICommandEndRenderPass(Data.LocalRHIRenderPass); } Data.LocalRHIRenderPass = nullptr; } FRHIParallelRenderPassCommandList& BeginParallelRenderPass(const FRHIRenderPassInfo& InInfo, const TCHAR* InName) { check(IsOutsideRenderPass()); FRHIParallelRenderPassCommandList& ParallelRenderPassCmdList = *(FRHIParallelRenderPassCommandList*)this; Data.LocalRHIParallelRenderPass = new(Alloc<FLocalCmdListParallelRenderPass>()) FLocalCmdListParallelRenderPass; CacheActiveRenderTargets(InInfo); if (Bypass()) { Data.LocalRHIParallelRenderPass->RenderPass = CMD_CONTEXT(RHIBeginParallelRenderPass)(InInfo, InName); } else { TCHAR* NameCopy = AllocString(InName); new (AllocCommand<FRHICommandBeginParallelRenderPass>()) FRHICommandBeginParallelRenderPass(InInfo, Data.LocalRHIParallelRenderPass, NameCopy); } return ParallelRenderPassCmdList; } void EndParallelRenderPass(FRHIParallelRenderPassCommandList& ParallelRenderPass) { check(Data.LocalRHIParallelRenderPass); if (Bypass()) { CMD_CONTEXT(RHIEndParallelRenderPass)(Data.LocalRHIParallelRenderPass->RenderPass); } else { // Cmd list deletion happens during FRHICommandEndRenderPass::Execute() new (AllocCommand<FRHICommandEndParallelRenderPass>()) FRHICommandEndParallelRenderPass(Data.LocalRHIParallelRenderPass); } Data.LocalRHIParallelRenderPass = nullptr; } // These 6 are special in that they must be called on the immediate command list and they force a flush only when we are not doing RHI thread void BeginScene(); void EndScene(); void BeginDrawingViewport(FViewportRHIParamRef Viewport, FTextureRHIParamRef RenderTargetRHI); void EndDrawingViewport(FViewportRHIParamRef Viewport, bool bPresent, bool bLockToVsync); void BeginFrame(); void EndFrame(); FORCEINLINE_DEBUGGABLE void PushEvent(const TCHAR* Name, FColor Color) { if (Bypass()) { CMD_CONTEXT(RHIPushEvent)(Name, Color); return; } TCHAR* NameCopy = AllocString(Name); new (AllocCommand<FRHICommandPushEvent<ECmdList::EGfx>>()) FRHICommandPushEvent<ECmdList::EGfx>(NameCopy, Color); } FORCEINLINE_DEBUGGABLE void PopEvent() { if (Bypass()) { CMD_CONTEXT(RHIPopEvent)(); return; } new (AllocCommand<FRHICommandPopEvent<ECmdList::EGfx>>()) FRHICommandPopEvent<ECmdList::EGfx>(); } FORCEINLINE_DEBUGGABLE void RHIInvalidateCachedState() { if (Bypass()) { CMD_CONTEXT(RHIInvalidateCachedState)(); return; } new (AllocCommand<FRHICommandInvalidateCachedState>()) FRHICommandInvalidateCachedState(); } FORCEINLINE_DEBUGGABLE void BreakPoint() { #if !UE_BUILD_SHIPPING if (Bypass()) { if (FPlatformMisc::IsDebuggerPresent()) { FPlatformMisc::DebugBreak(); } return; } new (AllocCommand<FRHICommandDebugBreak>()) FRHICommandDebugBreak(); #endif } // NvFlow begin FORCEINLINE_DEBUGGABLE void NvFlowWork(void(*WorkFunc)(void*,SIZE_T,IRHICommandContext*), void* ParamData, SIZE_T NumBytes) { if (Bypass()) { CMD_CONTEXT(NvFlowWork)(WorkFunc, ParamData, NumBytes); return; } // need local copy void* UseData = ParamData; if (NumBytes > 0u) { UseData = Alloc(NumBytes, 16u); FMemory::Memcpy(UseData, ParamData, NumBytes); } new (AllocCommand<FRHICommandNvFlowWork>()) FRHICommandNvFlowWork(WorkFunc, UseData, NumBytes); } // NvFlow end // NVCHANGE_BEGIN: Add VXGI #if WITH_GFSDK_VXGI FORCEINLINE_DEBUGGABLE void VXGICleanupAfterVoxelization() { if (Bypass()) { CMD_CONTEXT(RHIVXGICleanupAfterVoxelization)(); return; } new (AllocCommand<FRHIVXGICleanupAfterVoxelization>()) FRHIVXGICleanupAfterVoxelization(); } FORCEINLINE_DEBUGGABLE void SetViewportsAndScissorRects(uint32 Count, const FViewportBounds* Viewports, const FScissorRect* ScissorRects) { if (Bypass()) { CMD_CONTEXT(RHISetViewportsAndScissorRects)(Count, Viewports, ScissorRects); return; } new (AllocCommand<FRHISetViewportsAndScissorRects>()) FRHISetViewportsAndScissorRects(Count, Viewports, ScissorRects); } FORCEINLINE_DEBUGGABLE void DispatchIndirectComputeShaderStructured(FStructuredBufferRHIParamRef ArgumentBuffer, uint32 ArgumentOffset) { if (Bypass()) { CMD_CONTEXT(RHIDispatchIndirectComputeShaderStructured)(ArgumentBuffer, ArgumentOffset); return; } new (AllocCommand<FRHIDispatchIndirectComputeShaderStructured>()) FRHIDispatchIndirectComputeShaderStructured(ArgumentBuffer, ArgumentOffset); } FORCEINLINE_DEBUGGABLE void CopyStructuredBufferData(FStructuredBufferRHIParamRef DestBuffer, uint32 DestOffset, FStructuredBufferRHIParamRef SrcBuffer, uint32 SrcOffset, uint32 DataSize) { if (Bypass()) { CMD_CONTEXT(RHICopyStructuredBufferData)(DestBuffer, DestOffset, SrcBuffer, SrcOffset, DataSize); return; } new (AllocCommand<FRHICopyStructuredBufferData>()) FRHICopyStructuredBufferData(DestBuffer, DestOffset, SrcBuffer, SrcOffset, DataSize); } FORCEINLINE_DEBUGGABLE void ExecuteVxgiRenderingCommand(NVRHI::IRenderThreadCommand* Command) { if (Bypass()) { CMD_CONTEXT(RHIExecuteVxgiRenderingCommand)(Command); return; } new (AllocCommand<FRHIExecuteVxgiRenderingCommand>()) FRHIExecuteVxgiRenderingCommand(Command); } #endif // NVCHANGE_END: Add VXGI // NVCHANGE_BEGIN: Nvidia Volumetric Lighting #if WITH_NVVOLUMETRICLIGHTING FORCEINLINE_DEBUGGABLE void BeginAccumulation(FTextureRHIParamRef SceneDepthTextureRHI, const TArray<NvVl::ViewerDesc>& ViewerDescs, const NvVl::MediumDesc& MediumDesc, NvVl::DebugFlags DebugFlags) { if (Bypass()) { if (GNVVolumetricLightingRHI) { GNVVolumetricLightingRHI->BeginAccumulation(SceneDepthTextureRHI, ViewerDescs, MediumDesc, DebugFlags); } return; } new (AllocCommand<FRHICommandBeginAccumulation>()) FRHICommandBeginAccumulation(SceneDepthTextureRHI, ViewerDescs, MediumDesc, DebugFlags); } FORCEINLINE_DEBUGGABLE void RenderVolume(const TArray<FTextureRHIParamRef>& ShadowMapTextures, const NvVl::ShadowMapDesc& ShadowMapDesc, const NvVl::LightDesc& LightDesc, const NvVl::VolumeDesc& VolumeDesc) { if (Bypass()) { if (GNVVolumetricLightingRHI) { GNVVolumetricLightingRHI->RenderVolume(ShadowMapTextures, ShadowMapDesc, LightDesc, VolumeDesc); } return; } new (AllocCommand<FRHICommandRenderVolume>()) FRHICommandRenderVolume(ShadowMapTextures, ShadowMapDesc, LightDesc, VolumeDesc); } FORCEINLINE_DEBUGGABLE void EndAccumulation() { if (Bypass()) { if (GNVVolumetricLightingRHI) { GNVVolumetricLightingRHI->EndAccumulation(); } return; } new (AllocCommand<FRHICommandEndAccumulation>()) FRHICommandEndAccumulation(); } FORCEINLINE_DEBUGGABLE void ApplyLighting(FTextureRHIParamRef SceneColorSurfaceRHI, const NvVl::PostprocessDesc& PostprocessDesc) { if (Bypass()) { if (GNVVolumetricLightingRHI) { GNVVolumetricLightingRHI->ApplyLighting(SceneColorSurfaceRHI, PostprocessDesc); } return; } new (AllocCommand<FRHICommandApplyLighting>()) FRHICommandApplyLighting(SceneColorSurfaceRHI, PostprocessDesc); } #endif // NVCHANGE_END: Nvidia Volumetric Lighting }; class RHI_API FRHIAsyncComputeCommandList : public FRHICommandListBase { public: /** Custom new/delete with recycling */ void* operator new(size_t Size); void operator delete(void *RawMemory); FORCEINLINE_DEBUGGABLE void SetShaderUniformBuffer(FComputeShaderRHIParamRef Shader, uint32 BaseIndex, FUniformBufferRHIParamRef UniformBuffer) { if (Bypass()) { COMPUTE_CONTEXT(RHISetShaderUniformBuffer)(Shader, BaseIndex, UniformBuffer); return; } new (AllocCommand<FRHICommandSetShaderUniformBuffer<FComputeShaderRHIParamRef, ECmdList::ECompute> >()) FRHICommandSetShaderUniformBuffer<FComputeShaderRHIParamRef, ECmdList::ECompute>(Shader, BaseIndex, UniformBuffer); } FORCEINLINE void SetShaderUniformBuffer(FComputeShaderRHIRef& Shader, uint32 BaseIndex, FUniformBufferRHIParamRef UniformBuffer) { SetShaderUniformBuffer(Shader.GetReference(), BaseIndex, UniformBuffer); } FORCEINLINE_DEBUGGABLE void SetShaderParameter(FComputeShaderRHIParamRef Shader, uint32 BufferIndex, uint32 BaseIndex, uint32 NumBytes, const void* NewValue) { if (Bypass()) { COMPUTE_CONTEXT(RHISetShaderParameter)(Shader, BufferIndex, BaseIndex, NumBytes, NewValue); return; } void* UseValue = Alloc(NumBytes, 16); FMemory::Memcpy(UseValue, NewValue, NumBytes); new (AllocCommand<FRHICommandSetShaderParameter<FComputeShaderRHIParamRef, ECmdList::ECompute> >()) FRHICommandSetShaderParameter<FComputeShaderRHIParamRef, ECmdList::ECompute>(Shader, BufferIndex, BaseIndex, NumBytes, UseValue); } FORCEINLINE void SetShaderParameter(FComputeShaderRHIRef& Shader, uint32 BufferIndex, uint32 BaseIndex, uint32 NumBytes, const void* NewValue) { SetShaderParameter(Shader.GetReference(), BufferIndex, BaseIndex, NumBytes, NewValue); } FORCEINLINE_DEBUGGABLE void SetShaderTexture(FComputeShaderRHIParamRef Shader, uint32 TextureIndex, FTextureRHIParamRef Texture) { if (Bypass()) { COMPUTE_CONTEXT(RHISetShaderTexture)(Shader, TextureIndex, Texture); return; } new (AllocCommand<FRHICommandSetShaderTexture<FComputeShaderRHIParamRef, ECmdList::ECompute> >()) FRHICommandSetShaderTexture<FComputeShaderRHIParamRef, ECmdList::ECompute>(Shader, TextureIndex, Texture); } FORCEINLINE_DEBUGGABLE void SetShaderResourceViewParameter(FComputeShaderRHIParamRef Shader, uint32 SamplerIndex, FShaderResourceViewRHIParamRef SRV) { if (Bypass()) { COMPUTE_CONTEXT(RHISetShaderResourceViewParameter)(Shader, SamplerIndex, SRV); return; } new (AllocCommand<FRHICommandSetShaderResourceViewParameter<FComputeShaderRHIParamRef, ECmdList::ECompute> >()) FRHICommandSetShaderResourceViewParameter<FComputeShaderRHIParamRef, ECmdList::ECompute>(Shader, SamplerIndex, SRV); } FORCEINLINE_DEBUGGABLE void SetShaderSampler(FComputeShaderRHIParamRef Shader, uint32 SamplerIndex, FSamplerStateRHIParamRef State) { if (Bypass()) { COMPUTE_CONTEXT(RHISetShaderSampler)(Shader, SamplerIndex, State); return; } new (AllocCommand<FRHICommandSetShaderSampler<FComputeShaderRHIParamRef, ECmdList::ECompute> >()) FRHICommandSetShaderSampler<FComputeShaderRHIParamRef, ECmdList::ECompute>(Shader, SamplerIndex, State); } FORCEINLINE_DEBUGGABLE void SetUAVParameter(FComputeShaderRHIParamRef Shader, uint32 UAVIndex, FUnorderedAccessViewRHIParamRef UAV) { if (Bypass()) { COMPUTE_CONTEXT(RHISetUAVParameter)(Shader, UAVIndex, UAV); return; } new (AllocCommand<FRHICommandSetUAVParameter<FComputeShaderRHIParamRef, ECmdList::ECompute> >()) FRHICommandSetUAVParameter<FComputeShaderRHIParamRef, ECmdList::ECompute>(Shader, UAVIndex, UAV); } FORCEINLINE_DEBUGGABLE void SetUAVParameter(FComputeShaderRHIParamRef Shader, uint32 UAVIndex, FUnorderedAccessViewRHIParamRef UAV, uint32 InitialCount) { if (Bypass()) { COMPUTE_CONTEXT(RHISetUAVParameter)(Shader, UAVIndex, UAV, InitialCount); return; } new (AllocCommand<FRHICommandSetUAVParameter_IntialCount<FComputeShaderRHIParamRef, ECmdList::ECompute> >()) FRHICommandSetUAVParameter_IntialCount<FComputeShaderRHIParamRef, ECmdList::ECompute>(Shader, UAVIndex, UAV, InitialCount); } FORCEINLINE_DEBUGGABLE void SetComputeShader(FComputeShaderRHIParamRef ComputeShader) { if (Bypass()) { COMPUTE_CONTEXT(RHISetComputeShader)(ComputeShader); return; } new (AllocCommand<FRHICommandSetComputeShader<ECmdList::ECompute> >()) FRHICommandSetComputeShader<ECmdList::ECompute>(ComputeShader); } FORCEINLINE_DEBUGGABLE void SetComputePipelineState(FComputePipelineState* ComputePipelineState) { if (Bypass()) { extern FRHIComputePipelineState* ExecuteSetComputePipelineState(FComputePipelineState* ComputePipelineState); FRHIComputePipelineState* RHIComputePipelineState = ExecuteSetComputePipelineState(ComputePipelineState); COMPUTE_CONTEXT(RHISetComputePipelineState)(RHIComputePipelineState); return; } new (AllocCommand<FRHICommandSetComputePipelineState<ECmdList::ECompute> >()) FRHICommandSetComputePipelineState<ECmdList::ECompute>(ComputePipelineState); } FORCEINLINE_DEBUGGABLE void SetAsyncComputeBudget(EAsyncComputeBudget Budget) { if (Bypass()) { COMPUTE_CONTEXT(RHISetAsyncComputeBudget)(Budget); return; } new (AllocCommand<FRHICommandSetAsyncComputeBudget<ECmdList::ECompute>>()) FRHICommandSetAsyncComputeBudget<ECmdList::ECompute>(Budget); } FORCEINLINE_DEBUGGABLE void DispatchComputeShader(uint32 ThreadGroupCountX, uint32 ThreadGroupCountY, uint32 ThreadGroupCountZ) { if (Bypass()) { COMPUTE_CONTEXT(RHIDispatchComputeShader)(ThreadGroupCountX, ThreadGroupCountY, ThreadGroupCountZ); return; } new (AllocCommand<FRHICommandDispatchComputeShader<ECmdList::ECompute> >()) FRHICommandDispatchComputeShader<ECmdList::ECompute>(ThreadGroupCountX, ThreadGroupCountY, ThreadGroupCountZ); } FORCEINLINE_DEBUGGABLE void DispatchIndirectComputeShader(FVertexBufferRHIParamRef ArgumentBuffer, uint32 ArgumentOffset) { if (Bypass()) { COMPUTE_CONTEXT(RHIDispatchIndirectComputeShader)(ArgumentBuffer, ArgumentOffset); return; } new (AllocCommand<FRHICommandDispatchIndirectComputeShader<ECmdList::ECompute> >()) FRHICommandDispatchIndirectComputeShader<ECmdList::ECompute>(ArgumentBuffer, ArgumentOffset); } FORCEINLINE_DEBUGGABLE void TransitionResource(EResourceTransitionAccess TransitionType, EResourceTransitionPipeline TransitionPipeline, FUnorderedAccessViewRHIParamRef InUAV, FComputeFenceRHIParamRef WriteFence) { FUnorderedAccessViewRHIParamRef UAV = InUAV; if (Bypass()) { COMPUTE_CONTEXT(RHITransitionResources)(TransitionType, TransitionPipeline, &UAV, 1, WriteFence); return; } // Allocate space to hold the single UAV pointer inline in the command list itself. FUnorderedAccessViewRHIParamRef* UAVArray = (FUnorderedAccessViewRHIParamRef*)Alloc(sizeof(FUnorderedAccessViewRHIParamRef), alignof(FUnorderedAccessViewRHIParamRef)); UAVArray[0] = UAV; new (AllocCommand<FRHICommandTransitionUAVs<ECmdList::ECompute> >()) FRHICommandTransitionUAVs<ECmdList::ECompute>(TransitionType, TransitionPipeline, UAVArray, 1, WriteFence); } FORCEINLINE_DEBUGGABLE void TransitionResource(EResourceTransitionAccess TransitionType, EResourceTransitionPipeline TransitionPipeline, FUnorderedAccessViewRHIParamRef InUAV) { TransitionResource(TransitionType, TransitionPipeline, InUAV, nullptr); } FORCEINLINE_DEBUGGABLE void TransitionResources(EResourceTransitionAccess TransitionType, EResourceTransitionPipeline TransitionPipeline, FUnorderedAccessViewRHIParamRef* InUAVs, int32 NumUAVs, FComputeFenceRHIParamRef WriteFence) { if (Bypass()) { COMPUTE_CONTEXT(RHITransitionResources)(TransitionType, TransitionPipeline, InUAVs, NumUAVs, WriteFence); return; } // Allocate space to hold the list UAV pointers inline in the command list itself. FUnorderedAccessViewRHIParamRef* UAVArray = (FUnorderedAccessViewRHIParamRef*)Alloc(sizeof(FUnorderedAccessViewRHIParamRef) * NumUAVs, alignof(FUnorderedAccessViewRHIParamRef)); for (int32 Index = 0; Index < NumUAVs; ++Index) { UAVArray[Index] = InUAVs[Index]; } new (AllocCommand<FRHICommandTransitionUAVs<ECmdList::ECompute> >()) FRHICommandTransitionUAVs<ECmdList::ECompute>(TransitionType, TransitionPipeline, UAVArray, NumUAVs, WriteFence); } FORCEINLINE_DEBUGGABLE void TransitionResources(EResourceTransitionAccess TransitionType, EResourceTransitionPipeline TransitionPipeline, FUnorderedAccessViewRHIParamRef* InUAVs, int32 NumUAVs) { TransitionResources(TransitionType, TransitionPipeline, InUAVs, NumUAVs, nullptr); } FORCEINLINE_DEBUGGABLE void PushEvent(const TCHAR* Name, FColor Color) { if (Bypass()) { COMPUTE_CONTEXT(RHIPushEvent)(Name, Color); return; } TCHAR* NameCopy = AllocString(Name); new (AllocCommand<FRHICommandPushEvent<ECmdList::ECompute> >()) FRHICommandPushEvent<ECmdList::ECompute>(NameCopy, Color); } FORCEINLINE_DEBUGGABLE void PopEvent() { if (Bypass()) { COMPUTE_CONTEXT(RHIPopEvent)(); return; } new (AllocCommand<FRHICommandPopEvent<ECmdList::ECompute> >()) FRHICommandPopEvent<ECmdList::ECompute>(); } FORCEINLINE_DEBUGGABLE void BreakPoint() { #if !UE_BUILD_SHIPPING if (Bypass()) { if (FPlatformMisc::IsDebuggerPresent()) { FPlatformMisc::DebugBreak(); } return; } new (AllocCommand<FRHICommandDebugBreak>()) FRHICommandDebugBreak(); #endif } FORCEINLINE_DEBUGGABLE void SubmitCommandsHint() { if (Bypass()) { COMPUTE_CONTEXT(RHISubmitCommandsHint)(); return; } new (AllocCommand<FRHICommandSubmitCommandsHint<ECmdList::ECompute>>()) FRHICommandSubmitCommandsHint<ECmdList::ECompute>(); } FORCEINLINE_DEBUGGABLE void WaitComputeFence(FComputeFenceRHIParamRef WaitFence) { if (Bypass()) { COMPUTE_CONTEXT(RHIWaitComputeFence)(WaitFence); return; } new (AllocCommand<FRHICommandWaitComputeFence<ECmdList::ECompute>>()) FRHICommandWaitComputeFence<ECmdList::ECompute>(WaitFence); } }; namespace EImmediateFlushType { enum Type { WaitForOutstandingTasksOnly = 0, DispatchToRHIThread, WaitForDispatchToRHIThread, FlushRHIThread, FlushRHIThreadFlushResources }; }; class FScopedRHIThreadStaller { class FRHICommandListImmediate* Immed; // non-null if we need to unstall public: FScopedRHIThreadStaller(class FRHICommandListImmediate& InImmed); ~FScopedRHIThreadStaller(); }; class RHI_API FRHICommandListImmediate : public FRHICommandList { friend class FRHICommandListExecutor; FRHICommandListImmediate() { Data.Type = FRHICommandListBase::FCommonData::ECmdListType::Immediate; } ~FRHICommandListImmediate() { check(!HasCommands()); } public: void ImmediateFlush(EImmediateFlushType::Type FlushType); bool StallRHIThread(); void UnStallRHIThread(); static bool IsStalled(); void SetCurrentStat(TStatId Stat); static FGraphEventRef RenderThreadTaskFence(); static void WaitOnRenderThreadTaskFence(FGraphEventRef& Fence); static bool AnyRenderThreadTasksOutstanding(); FGraphEventRef RHIThreadFence(bool bSetLockFence = false); //Queue the given async compute commandlists in order with the current immediate commandlist void QueueAsyncCompute(FRHIAsyncComputeCommandList& RHIComputeCmdList); FORCEINLINE FSamplerStateRHIRef CreateSamplerState(const FSamplerStateInitializerRHI& Initializer) { LLM_SCOPE(ELLMTag::RHIMisc); return RHICreateSamplerState(Initializer); } FORCEINLINE FRasterizerStateRHIRef CreateRasterizerState(const FRasterizerStateInitializerRHI& Initializer) { LLM_SCOPE(ELLMTag::RHIMisc); return RHICreateRasterizerState(Initializer); } FORCEINLINE FDepthStencilStateRHIRef CreateDepthStencilState(const FDepthStencilStateInitializerRHI& Initializer) { LLM_SCOPE(ELLMTag::RHIMisc); return RHICreateDepthStencilState(Initializer); } FORCEINLINE FBlendStateRHIRef CreateBlendState(const FBlendStateInitializerRHI& Initializer) { LLM_SCOPE(ELLMTag::RHIMisc); return RHICreateBlendState(Initializer); } FORCEINLINE FVertexDeclarationRHIRef CreateVertexDeclaration(const FVertexDeclarationElementList& Elements) { LLM_SCOPE(ELLMTag::Shaders); return GDynamicRHI->CreateVertexDeclaration_RenderThread(*this, Elements); } FORCEINLINE FPixelShaderRHIRef CreatePixelShader(const TArray<uint8>& Code) { LLM_SCOPE(ELLMTag::Shaders); return GDynamicRHI->CreatePixelShader_RenderThread(*this, Code); } FORCEINLINE FPixelShaderRHIRef CreatePixelShader(FRHIShaderLibraryParamRef Library, FSHAHash Hash) { LLM_SCOPE(ELLMTag::Shaders); return GDynamicRHI->CreatePixelShader_RenderThread(*this, Library, Hash); } FORCEINLINE FVertexShaderRHIRef CreateVertexShader(const TArray<uint8>& Code) { LLM_SCOPE(ELLMTag::Shaders); return GDynamicRHI->CreateVertexShader_RenderThread(*this, Code); } FORCEINLINE FVertexShaderRHIRef CreateVertexShader(FRHIShaderLibraryParamRef Library, FSHAHash Hash) { LLM_SCOPE(ELLMTag::Shaders); return GDynamicRHI->CreateVertexShader_RenderThread(*this, Library, Hash); } FORCEINLINE FHullShaderRHIRef CreateHullShader(const TArray<uint8>& Code) { LLM_SCOPE(ELLMTag::Shaders); return GDynamicRHI->CreateHullShader_RenderThread(*this, Code); } FORCEINLINE FHullShaderRHIRef CreateHullShader(FRHIShaderLibraryParamRef Library, FSHAHash Hash) { LLM_SCOPE(ELLMTag::Shaders); return GDynamicRHI->CreateHullShader_RenderThread(*this, Library, Hash); } FORCEINLINE FDomainShaderRHIRef CreateDomainShader(const TArray<uint8>& Code) { LLM_SCOPE(ELLMTag::Shaders); return GDynamicRHI->CreateDomainShader_RenderThread(*this, Code); } FORCEINLINE FDomainShaderRHIRef CreateDomainShader(FRHIShaderLibraryParamRef Library, FSHAHash Hash) { LLM_SCOPE(ELLMTag::Shaders); return GDynamicRHI->CreateDomainShader_RenderThread(*this, Library, Hash); } FORCEINLINE FGeometryShaderRHIRef CreateGeometryShader(const TArray<uint8>& Code) { LLM_SCOPE(ELLMTag::Shaders); return GDynamicRHI->CreateGeometryShader_RenderThread(*this, Code); } FORCEINLINE FGeometryShaderRHIRef CreateGeometryShader(FRHIShaderLibraryParamRef Library, FSHAHash Hash) { LLM_SCOPE(ELLMTag::Shaders); return GDynamicRHI->CreateGeometryShader_RenderThread(*this, Library, Hash); } FORCEINLINE FGeometryShaderRHIRef CreateGeometryShaderWithStreamOutput(const TArray<uint8>& Code, const FStreamOutElementList& ElementList, uint32 NumStrides, const uint32* Strides, int32 RasterizedStream) { LLM_SCOPE(ELLMTag::Shaders); return GDynamicRHI->CreateGeometryShaderWithStreamOutput_RenderThread(*this, Code, ElementList, NumStrides, Strides, RasterizedStream); } FORCEINLINE FGeometryShaderRHIRef CreateGeometryShaderWithStreamOutput(const FStreamOutElementList& ElementList, uint32 NumStrides, const uint32* Strides, int32 RasterizedStream, FRHIShaderLibraryParamRef Library, FSHAHash Hash) { LLM_SCOPE(ELLMTag::Shaders); return GDynamicRHI->CreateGeometryShaderWithStreamOutput_RenderThread(*this, ElementList, NumStrides, Strides, RasterizedStream, Library, Hash); } FORCEINLINE FComputeShaderRHIRef CreateComputeShader(const TArray<uint8>& Code) { LLM_SCOPE(ELLMTag::Shaders); return GDynamicRHI->CreateComputeShader_RenderThread(*this, Code); } FORCEINLINE FComputeShaderRHIRef CreateComputeShader(FRHIShaderLibraryParamRef Library, FSHAHash Hash) { LLM_SCOPE(ELLMTag::Shaders); return GDynamicRHI->CreateComputeShader_RenderThread(*this, Library, Hash); } FORCEINLINE FComputeFenceRHIRef CreateComputeFence(const FName& Name) { return GDynamicRHI->RHICreateComputeFence(Name); } FORCEINLINE FBoundShaderStateRHIRef CreateBoundShaderState(FVertexDeclarationRHIParamRef VertexDeclaration, FVertexShaderRHIParamRef VertexShader, FHullShaderRHIParamRef HullShader, FDomainShaderRHIParamRef DomainShader, FPixelShaderRHIParamRef PixelShader, FGeometryShaderRHIParamRef GeometryShader) { LLM_SCOPE(ELLMTag::Shaders); return RHICreateBoundShaderState(VertexDeclaration, VertexShader, HullShader, DomainShader, PixelShader, GeometryShader); } FORCEINLINE FGraphicsPipelineStateRHIRef CreateGraphicsPipelineState(const FGraphicsPipelineStateInitializer& Initializer) { LLM_SCOPE(ELLMTag::Shaders); return RHICreateGraphicsPipelineState(Initializer); } FORCEINLINE TRefCountPtr<FRHIComputePipelineState> CreateComputePipelineState(FRHIComputeShader* ComputeShader) { LLM_SCOPE(ELLMTag::Shaders); return RHICreateComputePipelineState(ComputeShader); } FORCEINLINE FUniformBufferRHIRef CreateUniformBuffer(const void* Contents, const FRHIUniformBufferLayout& Layout, EUniformBufferUsage Usage) { LLM_SCOPE(ELLMTag::RHIMisc); return RHICreateUniformBuffer(Contents, Layout, Usage); } FORCEINLINE FIndexBufferRHIRef CreateAndLockIndexBuffer(uint32 Stride, uint32 Size, uint32 InUsage, FRHIResourceCreateInfo& CreateInfo, void*& OutDataBuffer) { LLM_SCOPE(ELLMTag::Meshes); return GDynamicRHI->CreateAndLockIndexBuffer_RenderThread(*this, Stride, Size, InUsage, CreateInfo, OutDataBuffer); } FORCEINLINE FIndexBufferRHIRef CreateIndexBuffer(uint32 Stride, uint32 Size, uint32 InUsage, FRHIResourceCreateInfo& CreateInfo) { LLM_SCOPE(ELLMTag::Meshes); return GDynamicRHI->CreateIndexBuffer_RenderThread(*this, Stride, Size, InUsage, CreateInfo); } FORCEINLINE void* LockIndexBuffer(FIndexBufferRHIParamRef IndexBuffer, uint32 Offset, uint32 SizeRHI, EResourceLockMode LockMode) { LLM_SCOPE(ELLMTag::Meshes); return GDynamicRHI->LockIndexBuffer_RenderThread(*this, IndexBuffer, Offset, SizeRHI, LockMode); } FORCEINLINE void UnlockIndexBuffer(FIndexBufferRHIParamRef IndexBuffer) { GDynamicRHI->UnlockIndexBuffer_RenderThread(*this, IndexBuffer); } FORCEINLINE FVertexBufferRHIRef CreateAndLockVertexBuffer(uint32 Size, uint32 InUsage, FRHIResourceCreateInfo& CreateInfo, void*& OutDataBuffer) { LLM_SCOPE(ELLMTag::Meshes); return GDynamicRHI->CreateAndLockVertexBuffer_RenderThread(*this, Size, InUsage, CreateInfo, OutDataBuffer); } FORCEINLINE FVertexBufferRHIRef CreateVertexBuffer(uint32 Size, uint32 InUsage, FRHIResourceCreateInfo& CreateInfo) { LLM_SCOPE(ELLMTag::Meshes); return GDynamicRHI->CreateVertexBuffer_RenderThread(*this, Size, InUsage, CreateInfo); } FORCEINLINE void* LockVertexBuffer(FVertexBufferRHIParamRef VertexBuffer, uint32 Offset, uint32 SizeRHI, EResourceLockMode LockMode) { LLM_SCOPE(ELLMTag::Meshes); return GDynamicRHI->LockVertexBuffer_RenderThread(*this, VertexBuffer, Offset, SizeRHI, LockMode); } FORCEINLINE void UnlockVertexBuffer(FVertexBufferRHIParamRef VertexBuffer) { GDynamicRHI->UnlockVertexBuffer_RenderThread(*this, VertexBuffer); } FORCEINLINE void CopyVertexBuffer(FVertexBufferRHIParamRef SourceBuffer,FVertexBufferRHIParamRef DestBuffer) { QUICK_SCOPE_CYCLE_COUNTER(STAT_RHIMETHOD_CopyVertexBuffer_Flush); ImmediateFlush(EImmediateFlushType::FlushRHIThread); GDynamicRHI->RHICopyVertexBuffer(SourceBuffer,DestBuffer); } FORCEINLINE FStructuredBufferRHIRef CreateStructuredBuffer(uint32 Stride, uint32 Size, uint32 InUsage, FRHIResourceCreateInfo& CreateInfo) { LLM_SCOPE(ELLMTag::RHIMisc); return GDynamicRHI->CreateStructuredBuffer_RenderThread(*this, Stride, Size, InUsage, CreateInfo); } FORCEINLINE void* LockStructuredBuffer(FStructuredBufferRHIParamRef StructuredBuffer, uint32 Offset, uint32 SizeRHI, EResourceLockMode LockMode) { LLM_SCOPE(ELLMTag::RHIMisc); QUICK_SCOPE_CYCLE_COUNTER(STAT_RHIMETHOD_LockStructuredBuffer_Flush); ImmediateFlush(EImmediateFlushType::FlushRHIThread); return GDynamicRHI->RHILockStructuredBuffer(StructuredBuffer, Offset, SizeRHI, LockMode); } FORCEINLINE void UnlockStructuredBuffer(FStructuredBufferRHIParamRef StructuredBuffer) { LLM_SCOPE(ELLMTag::RHIMisc); QUICK_SCOPE_CYCLE_COUNTER(STAT_RHIMETHOD_UnlockStructuredBuffer_Flush); ImmediateFlush(EImmediateFlushType::FlushRHIThread); GDynamicRHI->RHIUnlockStructuredBuffer(StructuredBuffer); } FORCEINLINE FUnorderedAccessViewRHIRef CreateUnorderedAccessView(FStructuredBufferRHIParamRef StructuredBuffer, bool bUseUAVCounter, bool bAppendBuffer) { LLM_SCOPE(ELLMTag::RHIMisc); return GDynamicRHI->RHICreateUnorderedAccessView_RenderThread(*this, StructuredBuffer, bUseUAVCounter, bAppendBuffer); } FORCEINLINE FUnorderedAccessViewRHIRef CreateUnorderedAccessView(FTextureRHIParamRef Texture, uint32 MipLevel) { LLM_SCOPE(ELLMTag::RHIMisc); return GDynamicRHI->RHICreateUnorderedAccessView_RenderThread(*this, Texture, MipLevel); } FORCEINLINE FUnorderedAccessViewRHIRef CreateUnorderedAccessView(FVertexBufferRHIParamRef VertexBuffer, uint8 Format) { LLM_SCOPE(ELLMTag::RHIMisc); return GDynamicRHI->RHICreateUnorderedAccessView_RenderThread(*this, VertexBuffer, Format); } FORCEINLINE FShaderResourceViewRHIRef CreateShaderResourceView(FStructuredBufferRHIParamRef StructuredBuffer) { LLM_SCOPE(ELLMTag::RHIMisc); return GDynamicRHI->RHICreateShaderResourceView_RenderThread(*this, StructuredBuffer); } FORCEINLINE FShaderResourceViewRHIRef CreateShaderResourceView(FVertexBufferRHIParamRef VertexBuffer, uint32 Stride, uint8 Format) { LLM_SCOPE(ELLMTag::RHIMisc); return GDynamicRHI->CreateShaderResourceView_RenderThread(*this, VertexBuffer, Stride, Format); } FORCEINLINE FShaderResourceViewRHIRef CreateShaderResourceView(FIndexBufferRHIParamRef Buffer) { LLM_SCOPE(ELLMTag::RHIMisc); return GDynamicRHI->CreateShaderResourceView_RenderThread(*this, Buffer); } FORCEINLINE uint64 CalcTexture2DPlatformSize(uint32 SizeX, uint32 SizeY, uint8 Format, uint32 NumMips, uint32 NumSamples, uint32 Flags, uint32& OutAlign) { return RHICalcTexture2DPlatformSize(SizeX, SizeY, Format, NumMips, NumSamples, Flags, OutAlign); } FORCEINLINE uint64 CalcTexture3DPlatformSize(uint32 SizeX, uint32 SizeY, uint32 SizeZ, uint8 Format, uint32 NumMips, uint32 Flags, uint32& OutAlign) { return RHICalcTexture3DPlatformSize(SizeX, SizeY, SizeZ, Format, NumMips, Flags, OutAlign); } FORCEINLINE uint64 CalcTextureCubePlatformSize(uint32 Size, uint8 Format, uint32 NumMips, uint32 Flags, uint32& OutAlign) { return RHICalcTextureCubePlatformSize(Size, Format, NumMips, Flags, OutAlign); } FORCEINLINE void GetTextureMemoryStats(FTextureMemoryStats& OutStats) { RHIGetTextureMemoryStats(OutStats); } FORCEINLINE bool GetTextureMemoryVisualizeData(FColor* TextureData,int32 SizeX,int32 SizeY,int32 Pitch,int32 PixelSize) { QUICK_SCOPE_CYCLE_COUNTER(STAT_RHIMETHOD_GetTextureMemoryVisualizeData_Flush); ImmediateFlush(EImmediateFlushType::FlushRHIThread); return GDynamicRHI->RHIGetTextureMemoryVisualizeData(TextureData,SizeX,SizeY,Pitch,PixelSize); } FORCEINLINE FTextureReferenceRHIRef CreateTextureReference(FLastRenderTimeContainer* LastRenderTime) { LLM_SCOPE(ELLMTag::Textures); FScopedRHIThreadStaller StallRHIThread(*this); return GDynamicRHI->RHICreateTextureReference(LastRenderTime); } FORCEINLINE FTexture2DRHIRef CreateTexture2D(uint32 SizeX, uint32 SizeY, uint8 Format, uint32 NumMips, uint32 NumSamples, uint32 Flags, FRHIResourceCreateInfo& CreateInfo) { LLM_SCOPE((Flags & (TexCreate_RenderTargetable | TexCreate_DepthStencilTargetable)) != 0 ? ELLMTag::RenderTargets : ELLMTag::Textures); return GDynamicRHI->RHICreateTexture2D_RenderThread(*this, SizeX, SizeY, Format, NumMips, NumSamples, Flags, CreateInfo); } FORCEINLINE FTexture2DRHIRef CreateTextureExternal2D(uint32 SizeX, uint32 SizeY, uint8 Format, uint32 NumMips, uint32 NumSamples, uint32 Flags, FRHIResourceCreateInfo& CreateInfo) { return GDynamicRHI->RHICreateTextureExternal2D_RenderThread(*this, SizeX, SizeY, Format, NumMips, NumSamples, Flags, CreateInfo); } FORCEINLINE FStructuredBufferRHIRef CreateRTWriteMaskBuffer(FTexture2DRHIRef RenderTarget) { LLM_SCOPE(ELLMTag::RenderTargets); return GDynamicRHI->RHICreateRTWriteMaskBuffer(RenderTarget); } FORCEINLINE FTexture2DRHIRef AsyncCreateTexture2D(uint32 SizeX, uint32 SizeY, uint8 Format, uint32 NumMips, uint32 Flags, void** InitialMipData, uint32 NumInitialMips) { LLM_SCOPE((Flags & (TexCreate_RenderTargetable | TexCreate_DepthStencilTargetable)) != 0 ? ELLMTag::RenderTargets : ELLMTag::Textures); return GDynamicRHI->RHIAsyncCreateTexture2D(SizeX, SizeY, Format, NumMips, Flags, InitialMipData, NumInitialMips); } FORCEINLINE void CopySharedMips(FTexture2DRHIParamRef DestTexture2D, FTexture2DRHIParamRef SrcTexture2D) { LLM_SCOPE(ELLMTag::Textures); QUICK_SCOPE_CYCLE_COUNTER(STAT_RHIMETHOD_CopySharedMips_Flush); ImmediateFlush(EImmediateFlushType::FlushRHIThread); return GDynamicRHI->RHICopySharedMips(DestTexture2D, SrcTexture2D); } FORCEINLINE FTexture2DArrayRHIRef CreateTexture2DArray(uint32 SizeX, uint32 SizeY, uint32 SizeZ, uint8 Format, uint32 NumMips, uint32 Flags, FRHIResourceCreateInfo& CreateInfo) { LLM_SCOPE((Flags & (TexCreate_RenderTargetable | TexCreate_DepthStencilTargetable)) != 0 ? ELLMTag::RenderTargets : ELLMTag::Textures); return GDynamicRHI->RHICreateTexture2DArray_RenderThread(*this, SizeX, SizeY, SizeZ, Format, NumMips, Flags, CreateInfo); } FORCEINLINE FTexture3DRHIRef CreateTexture3D(uint32 SizeX, uint32 SizeY, uint32 SizeZ, uint8 Format, uint32 NumMips, uint32 Flags, FRHIResourceCreateInfo& CreateInfo) { LLM_SCOPE((Flags & (TexCreate_RenderTargetable | TexCreate_DepthStencilTargetable)) != 0 ? ELLMTag::RenderTargets : ELLMTag::Textures); return GDynamicRHI->RHICreateTexture3D_RenderThread(*this, SizeX, SizeY, SizeZ, Format, NumMips, Flags, CreateInfo); } FORCEINLINE void GetResourceInfo(FTextureRHIParamRef Ref, FRHIResourceInfo& OutInfo) { return RHIGetResourceInfo(Ref, OutInfo); } FORCEINLINE FShaderResourceViewRHIRef CreateShaderResourceView(FTexture2DRHIParamRef Texture2DRHI, uint8 MipLevel) { LLM_SCOPE(ELLMTag::RHIMisc); return GDynamicRHI->RHICreateShaderResourceView_RenderThread(*this, Texture2DRHI, MipLevel); } FORCEINLINE FShaderResourceViewRHIRef CreateShaderResourceView(FTexture2DRHIParamRef Texture2DRHI, uint8 MipLevel, uint8 NumMipLevels, uint8 Format) { LLM_SCOPE(ELLMTag::RHIMisc); return GDynamicRHI->RHICreateShaderResourceView_RenderThread(*this, Texture2DRHI, MipLevel, NumMipLevels, Format); } FORCEINLINE FShaderResourceViewRHIRef CreateShaderResourceView(FTexture3DRHIParamRef Texture3DRHI, uint8 MipLevel) { LLM_SCOPE(ELLMTag::RHIMisc); return GDynamicRHI->RHICreateShaderResourceView_RenderThread(*this, Texture3DRHI, MipLevel); } FORCEINLINE FShaderResourceViewRHIRef CreateShaderResourceView(FTexture2DArrayRHIParamRef Texture2DArrayRHI, uint8 MipLevel) { LLM_SCOPE(ELLMTag::RHIMisc); return GDynamicRHI->RHICreateShaderResourceView_RenderThread(*this, Texture2DArrayRHI, MipLevel); } FORCEINLINE FShaderResourceViewRHIRef CreateShaderResourceView(FTextureCubeRHIParamRef TextureCubeRHI, uint8 MipLevel) { LLM_SCOPE(ELLMTag::RHIMisc); return GDynamicRHI->RHICreateShaderResourceView_RenderThread(*this, TextureCubeRHI, MipLevel); } FORCEINLINE void GenerateMips(FTextureRHIParamRef Texture) { QUICK_SCOPE_CYCLE_COUNTER(STAT_RHIMETHOD_GenerateMips_Flush); ImmediateFlush(EImmediateFlushType::FlushRHIThread); return GDynamicRHI->RHIGenerateMips(Texture); } FORCEINLINE uint32 ComputeMemorySize(FTextureRHIParamRef TextureRHI) { return RHIComputeMemorySize(TextureRHI); } FORCEINLINE FTexture2DRHIRef AsyncReallocateTexture2D(FTexture2DRHIParamRef Texture2D, int32 NewMipCount, int32 NewSizeX, int32 NewSizeY, FThreadSafeCounter* RequestStatus) { LLM_SCOPE(ELLMTag::Textures); return GDynamicRHI->AsyncReallocateTexture2D_RenderThread(*this, Texture2D, NewMipCount, NewSizeX, NewSizeY, RequestStatus); } FORCEINLINE ETextureReallocationStatus FinalizeAsyncReallocateTexture2D(FTexture2DRHIParamRef Texture2D, bool bBlockUntilCompleted) { LLM_SCOPE(ELLMTag::Textures); return GDynamicRHI->FinalizeAsyncReallocateTexture2D_RenderThread(*this, Texture2D, bBlockUntilCompleted); } FORCEINLINE ETextureReallocationStatus CancelAsyncReallocateTexture2D(FTexture2DRHIParamRef Texture2D, bool bBlockUntilCompleted) { return GDynamicRHI->CancelAsyncReallocateTexture2D_RenderThread(*this, Texture2D, bBlockUntilCompleted); } FORCEINLINE void* LockTexture2D(FTexture2DRHIParamRef Texture, uint32 MipIndex, EResourceLockMode LockMode, uint32& DestStride, bool bLockWithinMiptail, bool bFlushRHIThread = true) { LLM_SCOPE(ELLMTag::Textures); return GDynamicRHI->LockTexture2D_RenderThread(*this, Texture, MipIndex, LockMode, DestStride, bLockWithinMiptail, bFlushRHIThread); } FORCEINLINE void UnlockTexture2D(FTexture2DRHIParamRef Texture, uint32 MipIndex, bool bLockWithinMiptail, bool bFlushRHIThread = true) { GDynamicRHI->UnlockTexture2D_RenderThread(*this, Texture, MipIndex, bLockWithinMiptail, bFlushRHIThread); } FORCEINLINE void* LockTexture2DArray(FTexture2DArrayRHIParamRef Texture, uint32 TextureIndex, uint32 MipIndex, EResourceLockMode LockMode, uint32& DestStride, bool bLockWithinMiptail) { LLM_SCOPE(ELLMTag::Textures); QUICK_SCOPE_CYCLE_COUNTER(STAT_RHIMETHOD_LockTexture2DArray_Flush); ImmediateFlush(EImmediateFlushType::FlushRHIThread); return GDynamicRHI->RHILockTexture2DArray(Texture, TextureIndex, MipIndex, LockMode, DestStride, bLockWithinMiptail); } FORCEINLINE void UnlockTexture2DArray(FTexture2DArrayRHIParamRef Texture, uint32 TextureIndex, uint32 MipIndex, bool bLockWithinMiptail) { LLM_SCOPE(ELLMTag::Textures); QUICK_SCOPE_CYCLE_COUNTER(STAT_RHIMETHOD_UnlockTexture2DArray_Flush); ImmediateFlush(EImmediateFlushType::FlushRHIThread); GDynamicRHI->RHIUnlockTexture2DArray(Texture, TextureIndex, MipIndex, bLockWithinMiptail); } FORCEINLINE void UpdateTexture2D(FTexture2DRHIParamRef Texture, uint32 MipIndex, const struct FUpdateTextureRegion2D& UpdateRegion, uint32 SourcePitch, const uint8* SourceData) { LLM_SCOPED_TAG_WITH_STAT(STAT_TextureMemoryLLM, ELLMTracker::Default); checkf(UpdateRegion.DestX + UpdateRegion.Width <= Texture->GetSizeX(), TEXT("UpdateTexture2D out of bounds on X. Texture: %s, %i, %i, %i"), *Texture->GetName().ToString(), UpdateRegion.DestX, UpdateRegion.Width, Texture->GetSizeX()); checkf(UpdateRegion.DestY + UpdateRegion.Height <= Texture->GetSizeY(), TEXT("UpdateTexture2D out of bounds on Y. Texture: %s, %i, %i, %i"), *Texture->GetName().ToString(), UpdateRegion.DestY, UpdateRegion.Height, Texture->GetSizeY()); LLM_SCOPE(ELLMTag::Textures); GDynamicRHI->UpdateTexture2D_RenderThread(*this, Texture, MipIndex, UpdateRegion, SourcePitch, SourceData); } FORCEINLINE FUpdateTexture3DData BeginUpdateTexture3D(FTexture3DRHIParamRef Texture, uint32 MipIndex, const struct FUpdateTextureRegion3D& UpdateRegion) { checkf(UpdateRegion.DestX + UpdateRegion.Width <= Texture->GetSizeX(), TEXT("UpdateTexture3D out of bounds on X. Texture: %s, %i, %i, %i"), *Texture->GetName().ToString(), UpdateRegion.DestX, UpdateRegion.Width, Texture->GetSizeX()); checkf(UpdateRegion.DestY + UpdateRegion.Height <= Texture->GetSizeY(), TEXT("UpdateTexture3D out of bounds on Y. Texture: %s, %i, %i, %i"), *Texture->GetName().ToString(), UpdateRegion.DestY, UpdateRegion.Height, Texture->GetSizeY()); checkf(UpdateRegion.DestZ + UpdateRegion.Depth <= Texture->GetSizeZ(), TEXT("UpdateTexture3D out of bounds on Z. Texture: %s, %i, %i, %i"), *Texture->GetName().ToString(), UpdateRegion.DestZ, UpdateRegion.Depth, Texture->GetSizeZ()); LLM_SCOPE(ELLMTag::Textures); return GDynamicRHI->BeginUpdateTexture3D_RenderThread(*this, Texture, MipIndex, UpdateRegion); } FORCEINLINE void EndUpdateTexture3D(FUpdateTexture3DData& UpdateData) { LLM_SCOPE(ELLMTag::Textures); GDynamicRHI->EndUpdateTexture3D_RenderThread(*this, UpdateData); } FORCEINLINE void UpdateTexture3D(FTexture3DRHIParamRef Texture, uint32 MipIndex, const struct FUpdateTextureRegion3D& UpdateRegion, uint32 SourceRowPitch, uint32 SourceDepthPitch, const uint8* SourceData) { checkf(UpdateRegion.DestX + UpdateRegion.Width <= Texture->GetSizeX(), TEXT("UpdateTexture3D out of bounds on X. Texture: %s, %i, %i, %i"), *Texture->GetName().ToString(), UpdateRegion.DestX, UpdateRegion.Width, Texture->GetSizeX()); checkf(UpdateRegion.DestY + UpdateRegion.Height <= Texture->GetSizeY(), TEXT("UpdateTexture3D out of bounds on Y. Texture: %s, %i, %i, %i"), *Texture->GetName().ToString(), UpdateRegion.DestY, UpdateRegion.Height, Texture->GetSizeY()); checkf(UpdateRegion.DestZ + UpdateRegion.Depth <= Texture->GetSizeZ(), TEXT("UpdateTexture3D out of bounds on Z. Texture: %s, %i, %i, %i"), *Texture->GetName().ToString(), UpdateRegion.DestZ, UpdateRegion.Depth, Texture->GetSizeZ()); LLM_SCOPE(ELLMTag::Textures); GDynamicRHI->UpdateTexture3D_RenderThread(*this, Texture, MipIndex, UpdateRegion, SourceRowPitch, SourceDepthPitch, SourceData); } FORCEINLINE FTextureCubeRHIRef CreateTextureCube(uint32 Size, uint8 Format, uint32 NumMips, uint32 Flags, FRHIResourceCreateInfo& CreateInfo) { LLM_SCOPE((Flags & (TexCreate_RenderTargetable | TexCreate_DepthStencilTargetable)) != 0 ? ELLMTag::RenderTargets : ELLMTag::Textures); return GDynamicRHI->RHICreateTextureCube_RenderThread(*this, Size, Format, NumMips, Flags, CreateInfo); } FORCEINLINE FTextureCubeRHIRef CreateTextureCubeArray(uint32 Size, uint32 ArraySize, uint8 Format, uint32 NumMips, uint32 Flags, FRHIResourceCreateInfo& CreateInfo) { LLM_SCOPE((Flags & (TexCreate_RenderTargetable | TexCreate_DepthStencilTargetable)) != 0 ? ELLMTag::RenderTargets : ELLMTag::Textures); return GDynamicRHI->RHICreateTextureCubeArray_RenderThread(*this, Size, ArraySize, Format, NumMips, Flags, CreateInfo); } FORCEINLINE void* LockTextureCubeFace(FTextureCubeRHIParamRef Texture, uint32 FaceIndex, uint32 ArrayIndex, uint32 MipIndex, EResourceLockMode LockMode, uint32& DestStride, bool bLockWithinMiptail) { QUICK_SCOPE_CYCLE_COUNTER(STAT_RHIMETHOD_LockTextureCubeFace_Flush); ImmediateFlush(EImmediateFlushType::FlushRHIThread); return GDynamicRHI->RHILockTextureCubeFace(Texture, FaceIndex, ArrayIndex, MipIndex, LockMode, DestStride, bLockWithinMiptail); } FORCEINLINE void UnlockTextureCubeFace(FTextureCubeRHIParamRef Texture, uint32 FaceIndex, uint32 ArrayIndex, uint32 MipIndex, bool bLockWithinMiptail) { QUICK_SCOPE_CYCLE_COUNTER(STAT_RHIMETHOD_UnlockTextureCubeFace_Flush); ImmediateFlush(EImmediateFlushType::FlushRHIThread); GDynamicRHI->RHIUnlockTextureCubeFace(Texture, FaceIndex, ArrayIndex, MipIndex, bLockWithinMiptail); } FORCEINLINE void BindDebugLabelName(FTextureRHIParamRef Texture, const TCHAR* Name) { RHIBindDebugLabelName(Texture, Name); } FORCEINLINE void BindDebugLabelName(FUnorderedAccessViewRHIParamRef UnorderedAccessViewRHI, const TCHAR* Name) { RHIBindDebugLabelName(UnorderedAccessViewRHI, Name); } FORCEINLINE void ReadSurfaceData(FTextureRHIParamRef Texture,FIntRect Rect,TArray<FColor>& OutData,FReadSurfaceDataFlags InFlags) { QUICK_SCOPE_CYCLE_COUNTER(STAT_RHIMETHOD_ReadSurfaceData_Flush); ImmediateFlush(EImmediateFlushType::FlushRHIThread); GDynamicRHI->RHIReadSurfaceData(Texture,Rect,OutData,InFlags); } FORCEINLINE void ReadSurfaceData(FTextureRHIParamRef Texture, FIntRect Rect, TArray<FLinearColor>& OutData, FReadSurfaceDataFlags InFlags) { QUICK_SCOPE_CYCLE_COUNTER(STAT_RHIMETHOD_ReadSurfaceData_Flush); ImmediateFlush(EImmediateFlushType::FlushRHIThread); GDynamicRHI->RHIReadSurfaceData(Texture, Rect, OutData, InFlags); } FORCEINLINE void MapStagingSurface(FTextureRHIParamRef Texture,void*& OutData,int32& OutWidth,int32& OutHeight) { QUICK_SCOPE_CYCLE_COUNTER(STAT_RHIMETHOD_MapStagingSurface_Flush); ImmediateFlush(EImmediateFlushType::FlushRHIThread); GDynamicRHI->RHIMapStagingSurface(Texture,OutData,OutWidth,OutHeight); } FORCEINLINE void UnmapStagingSurface(FTextureRHIParamRef Texture) { QUICK_SCOPE_CYCLE_COUNTER(STAT_RHIMETHOD_UnmapStagingSurface_Flush); ImmediateFlush(EImmediateFlushType::FlushRHIThread); GDynamicRHI->RHIUnmapStagingSurface(Texture); } FORCEINLINE void ReadSurfaceFloatData(FTextureRHIParamRef Texture,FIntRect Rect,TArray<FFloat16Color>& OutData,ECubeFace CubeFace,int32 ArrayIndex,int32 MipIndex) { QUICK_SCOPE_CYCLE_COUNTER(STAT_RHIMETHOD_ReadSurfaceFloatData_Flush); ImmediateFlush(EImmediateFlushType::FlushRHIThread); GDynamicRHI->RHIReadSurfaceFloatData(Texture,Rect,OutData,CubeFace,ArrayIndex,MipIndex); } FORCEINLINE void Read3DSurfaceFloatData(FTextureRHIParamRef Texture,FIntRect Rect,FIntPoint ZMinMax,TArray<FFloat16Color>& OutData) { QUICK_SCOPE_CYCLE_COUNTER(STAT_RHIMETHOD_Read3DSurfaceFloatData_Flush); ImmediateFlush(EImmediateFlushType::FlushRHIThread); GDynamicRHI->RHIRead3DSurfaceFloatData(Texture,Rect,ZMinMax,OutData); } FORCEINLINE FRenderQueryRHIRef CreateRenderQuery(ERenderQueryType QueryType) { FScopedRHIThreadStaller StallRHIThread(*this); return GDynamicRHI->RHICreateRenderQuery(QueryType); } FORCEINLINE void AcquireTransientResource_RenderThread(FTextureRHIParamRef Texture) { if (!Texture->IsCommitted() ) { if (GSupportsTransientResourceAliasing) { GDynamicRHI->RHIAcquireTransientResource_RenderThread(Texture); } Texture->SetCommitted(true); } } FORCEINLINE void DiscardTransientResource_RenderThread(FTextureRHIParamRef Texture) { if (Texture->IsCommitted()) { if (GSupportsTransientResourceAliasing) { GDynamicRHI->RHIDiscardTransientResource_RenderThread(Texture); } Texture->SetCommitted(false); } } FORCEINLINE void AcquireTransientResource_RenderThread(FVertexBufferRHIParamRef Buffer) { if (!Buffer->IsCommitted()) { if (GSupportsTransientResourceAliasing) { GDynamicRHI->RHIAcquireTransientResource_RenderThread(Buffer); } Buffer->SetCommitted(true); } } FORCEINLINE void DiscardTransientResource_RenderThread(FVertexBufferRHIParamRef Buffer) { if (Buffer->IsCommitted()) { if (GSupportsTransientResourceAliasing) { GDynamicRHI->RHIDiscardTransientResource_RenderThread(Buffer); } Buffer->SetCommitted(false); } } FORCEINLINE void AcquireTransientResource_RenderThread(FStructuredBufferRHIParamRef Buffer) { if (!Buffer->IsCommitted()) { if (GSupportsTransientResourceAliasing) { GDynamicRHI->RHIAcquireTransientResource_RenderThread(Buffer); } Buffer->SetCommitted(true); } } FORCEINLINE void DiscardTransientResource_RenderThread(FStructuredBufferRHIParamRef Buffer) { if (Buffer->IsCommitted()) { if (GSupportsTransientResourceAliasing) { GDynamicRHI->RHIDiscardTransientResource_RenderThread(Buffer); } Buffer->SetCommitted(false); } } FORCEINLINE bool GetRenderQueryResult(FRenderQueryRHIParamRef RenderQuery, uint64& OutResult, bool bWait) { return RHIGetRenderQueryResult(RenderQuery, OutResult, bWait); } FORCEINLINE FTexture2DRHIRef GetViewportBackBuffer(FViewportRHIParamRef Viewport) { return RHIGetViewportBackBuffer(Viewport); } FORCEINLINE void AdvanceFrameForGetViewportBackBuffer(FViewportRHIParamRef Viewport) { return RHIAdvanceFrameForGetViewportBackBuffer(Viewport); } FORCEINLINE void AcquireThreadOwnership() { QUICK_SCOPE_CYCLE_COUNTER(STAT_RHIMETHOD_AcquireThreadOwnership_Flush); ImmediateFlush(EImmediateFlushType::FlushRHIThread); return GDynamicRHI->RHIAcquireThreadOwnership(); } FORCEINLINE void ReleaseThreadOwnership() { QUICK_SCOPE_CYCLE_COUNTER(STAT_RHIMETHOD_ReleaseThreadOwnership_Flush); ImmediateFlush(EImmediateFlushType::FlushRHIThread); return GDynamicRHI->RHIReleaseThreadOwnership(); } FORCEINLINE void FlushResources() { QUICK_SCOPE_CYCLE_COUNTER(STAT_RHIMETHOD_FlushResources_Flush); ImmediateFlush(EImmediateFlushType::FlushRHIThread); return GDynamicRHI->RHIFlushResources(); } FORCEINLINE uint32 GetGPUFrameCycles() { return RHIGetGPUFrameCycles(); } FORCEINLINE FViewportRHIRef CreateViewport(void* WindowHandle, uint32 SizeX, uint32 SizeY, bool bIsFullscreen, EPixelFormat PreferredPixelFormat) { LLM_SCOPE(ELLMTag::RenderTargets); return RHICreateViewport(WindowHandle, SizeX, SizeY, bIsFullscreen, PreferredPixelFormat); } FORCEINLINE void ResizeViewport(FViewportRHIParamRef Viewport, uint32 SizeX, uint32 SizeY, bool bIsFullscreen, EPixelFormat PreferredPixelFormat) { LLM_SCOPE(ELLMTag::RenderTargets); RHIResizeViewport(Viewport, SizeX, SizeY, bIsFullscreen, PreferredPixelFormat); } FORCEINLINE void Tick(float DeltaTime) { LLM_SCOPE(ELLMTag::RHIMisc); RHITick(DeltaTime); } FORCEINLINE void SetStreamOutTargets(uint32 NumTargets,const FVertexBufferRHIParamRef* VertexBuffers,const uint32* Offsets) { QUICK_SCOPE_CYCLE_COUNTER(STAT_RHIMETHOD_SetStreamOutTargets_Flush); ImmediateFlush(EImmediateFlushType::FlushRHIThread); GDynamicRHI->RHISetStreamOutTargets(NumTargets,VertexBuffers,Offsets); } FORCEINLINE void DiscardRenderTargets(bool Depth,bool Stencil,uint32 ColorBitMask) { GDynamicRHI->RHIDiscardRenderTargets(Depth,Stencil,ColorBitMask); } FORCEINLINE void BlockUntilGPUIdle() { QUICK_SCOPE_CYCLE_COUNTER(STAT_RHIMETHOD_BlockUntilGPUIdle_Flush); ImmediateFlush(EImmediateFlushType::FlushRHIThread); GDynamicRHI->RHIBlockUntilGPUIdle(); } FORCEINLINE_DEBUGGABLE void SubmitCommandsAndFlushGPU() { QUICK_SCOPE_CYCLE_COUNTER(STAT_RHIMETHOD_SubmitCommandsAndFlushGPU_Flush); ImmediateFlush(EImmediateFlushType::FlushRHIThread); GDynamicRHI->RHISubmitCommandsAndFlushGPU(); } FORCEINLINE void SuspendRendering() { RHISuspendRendering(); } FORCEINLINE void ResumeRendering() { RHIResumeRendering(); } FORCEINLINE bool IsRenderingSuspended() { QUICK_SCOPE_CYCLE_COUNTER(STAT_RHIMETHOD_IsRenderingSuspended_Flush); ImmediateFlush(EImmediateFlushType::FlushRHIThread); return GDynamicRHI->RHIIsRenderingSuspended(); } FORCEINLINE bool EnqueueDecompress(uint8_t* SrcBuffer, uint8_t* DestBuffer, int CompressedSize, void* ErrorCodeBuffer) { return GDynamicRHI->RHIEnqueueDecompress(SrcBuffer, DestBuffer, CompressedSize, ErrorCodeBuffer); } FORCEINLINE bool EnqueueCompress(uint8_t* SrcBuffer, uint8_t* DestBuffer, int UnCompressedSize, void* ErrorCodeBuffer) { return GDynamicRHI->RHIEnqueueCompress(SrcBuffer, DestBuffer, UnCompressedSize, ErrorCodeBuffer); } FORCEINLINE bool GetAvailableResolutions(FScreenResolutionArray& Resolutions, bool bIgnoreRefreshRate) { return RHIGetAvailableResolutions(Resolutions, bIgnoreRefreshRate); } FORCEINLINE void GetSupportedResolution(uint32& Width, uint32& Height) { RHIGetSupportedResolution(Width, Height); } FORCEINLINE void VirtualTextureSetFirstMipInMemory(FTexture2DRHIParamRef Texture, uint32 FirstMip) { FScopedRHIThreadStaller StallRHIThread(*this); GDynamicRHI->RHIVirtualTextureSetFirstMipInMemory(Texture, FirstMip); } FORCEINLINE void VirtualTextureSetFirstMipVisible(FTexture2DRHIParamRef Texture, uint32 FirstMip) { FScopedRHIThreadStaller StallRHIThread(*this); GDynamicRHI->RHIVirtualTextureSetFirstMipVisible(Texture, FirstMip); } FORCEINLINE void CopySubTextureRegion(FTexture2DRHIParamRef SourceTexture, FTexture2DRHIParamRef DestinationTexture, FBox2D SourceBox, FBox2D DestinationBox) { GDynamicRHI->RHICopySubTextureRegion_RenderThread(*this, SourceTexture, DestinationTexture, SourceBox, DestinationBox); } FORCEINLINE void ExecuteCommandList(FRHICommandList* CmdList) { FScopedRHIThreadStaller StallRHIThread(*this); GDynamicRHI->RHIExecuteCommandList(CmdList); } FORCEINLINE void SetResourceAliasability(EResourceAliasability AliasMode, FTextureRHIParamRef* InTextures, int32 NumTextures) { GDynamicRHI->RHISetResourceAliasability_RenderThread(*this, AliasMode, InTextures, NumTextures); } FORCEINLINE void* GetNativeDevice() { QUICK_SCOPE_CYCLE_COUNTER(STAT_RHIMETHOD_GetNativeDevice_Flush); ImmediateFlush(EImmediateFlushType::FlushRHIThread); return GDynamicRHI->RHIGetNativeDevice(); } FORCEINLINE class IRHICommandContext* GetDefaultContext() { return RHIGetDefaultContext(); } FORCEINLINE class IRHICommandContextContainer* GetCommandContextContainer(int32 Index, int32 Num) { return RHIGetCommandContextContainer(Index, Num); } void UpdateTextureReference(FTextureReferenceRHIParamRef TextureRef, FTextureRHIParamRef NewTexture); FORCEINLINE FRHIShaderLibraryRef CreateShaderLibrary(EShaderPlatform Platform, FString FilePath) { FScopedRHIThreadStaller StallRHIThread(*this); return GDynamicRHI->RHICreateShaderLibrary(Platform, FilePath); } }; // Single commandlist for async compute generation. In the future we may expand this to allow async compute command generation // on multiple threads at once. class RHI_API FRHIAsyncComputeCommandListImmediate : public FRHIAsyncComputeCommandList { public: //If RHIThread is enabled this will dispatch all current commands to the RHI Thread. If RHI thread is disabled //this will immediately execute the current commands. //This also queues a GPU Submission command as the final command in the dispatch. static void ImmediateDispatch(FRHIAsyncComputeCommandListImmediate& RHIComputeCmdList); private: }; // typedef to mark the recursive use of commandlists in the RHI implementations class RHI_API FRHICommandList_RecursiveHazardous : public FRHICommandList { FRHICommandList_RecursiveHazardous() { } public: FRHICommandList_RecursiveHazardous(IRHICommandContext *Context) { SetContext(Context); } }; // This controls if the cmd list bypass can be toggled at runtime. It is quite expensive to have these branches in there. #define CAN_TOGGLE_COMMAND_LIST_BYPASS (!UE_BUILD_SHIPPING && !UE_BUILD_TEST) class RHI_API FRHICommandListExecutor { public: enum { DefaultBypass = PLATFORM_RHITHREAD_DEFAULT_BYPASS }; FRHICommandListExecutor() : bLatchedBypass(!!DefaultBypass) , bLatchedUseParallelAlgorithms(false) { } static inline FRHICommandListImmediate& GetImmediateCommandList(); static inline FRHIAsyncComputeCommandListImmediate& GetImmediateAsyncComputeCommandList(); void ExecuteList(FRHICommandListBase& CmdList); void ExecuteList(FRHICommandListImmediate& CmdList); void LatchBypass(); static void WaitOnRHIThreadFence(FGraphEventRef& Fence); FORCEINLINE_DEBUGGABLE bool Bypass() { #if CAN_TOGGLE_COMMAND_LIST_BYPASS return bLatchedBypass; #else return !!DefaultBypass; #endif } FORCEINLINE_DEBUGGABLE bool UseParallelAlgorithms() { #if CAN_TOGGLE_COMMAND_LIST_BYPASS return bLatchedUseParallelAlgorithms; #else return FApp::ShouldUseThreadingForPerformance() && !Bypass(); #endif } static void CheckNoOutstandingCmdLists(); static bool IsRHIThreadActive(); static bool IsRHIThreadCompletelyFlushed(); private: void ExecuteInner(FRHICommandListBase& CmdList); friend class FExecuteRHIThreadTask; static void ExecuteInner_DoExecute(FRHICommandListBase& CmdList); bool bLatchedBypass; bool bLatchedUseParallelAlgorithms; friend class FRHICommandListBase; FThreadSafeCounter UIDCounter; FThreadSafeCounter OutstandingCmdListCount; FRHICommandListImmediate CommandListImmediate; FRHIAsyncComputeCommandListImmediate AsyncComputeCmdListImmediate; }; extern RHI_API FRHICommandListExecutor GRHICommandList; extern RHI_API FAutoConsoleTaskPriority CPrio_SceneRenderingTask; class FRenderTask { public: FORCEINLINE static ENamedThreads::Type GetDesiredThread() { return CPrio_SceneRenderingTask.Get(); } }; FORCEINLINE_DEBUGGABLE FRHICommandListImmediate& FRHICommandListExecutor::GetImmediateCommandList() { return GRHICommandList.CommandListImmediate; } FORCEINLINE_DEBUGGABLE FRHIAsyncComputeCommandListImmediate& FRHICommandListExecutor::GetImmediateAsyncComputeCommandList() { return GRHICommandList.AsyncComputeCmdListImmediate; } struct FScopedCommandListWaitForTasks { FRHICommandListImmediate& RHICmdList; bool bWaitForTasks; FScopedCommandListWaitForTasks(bool InbWaitForTasks, FRHICommandListImmediate& InRHICmdList = FRHICommandListExecutor::GetImmediateCommandList()) : RHICmdList(InRHICmdList) , bWaitForTasks(InbWaitForTasks) { } RHI_API ~FScopedCommandListWaitForTasks(); }; FORCEINLINE FVertexDeclarationRHIRef RHICreateVertexDeclaration(const FVertexDeclarationElementList& Elements) { return FRHICommandListExecutor::GetImmediateCommandList().CreateVertexDeclaration(Elements); } FORCEINLINE FPixelShaderRHIRef RHICreatePixelShader(const TArray<uint8>& Code) { return FRHICommandListExecutor::GetImmediateCommandList().CreatePixelShader(Code); } FORCEINLINE FPixelShaderRHIRef RHICreatePixelShader(FRHIShaderLibraryParamRef Library, FSHAHash Hash) { return FRHICommandListExecutor::GetImmediateCommandList().CreatePixelShader(Library, Hash); } FORCEINLINE FVertexShaderRHIRef RHICreateVertexShader(const TArray<uint8>& Code) { return FRHICommandListExecutor::GetImmediateCommandList().CreateVertexShader(Code); } FORCEINLINE FVertexShaderRHIRef RHICreateVertexShader(FRHIShaderLibraryParamRef Library, FSHAHash Hash) { return FRHICommandListExecutor::GetImmediateCommandList().CreateVertexShader(Library, Hash); } FORCEINLINE FHullShaderRHIRef RHICreateHullShader(const TArray<uint8>& Code) { return FRHICommandListExecutor::GetImmediateCommandList().CreateHullShader(Code); } FORCEINLINE FHullShaderRHIRef RHICreateHullShader(FRHIShaderLibraryParamRef Library, FSHAHash Hash) { return FRHICommandListExecutor::GetImmediateCommandList().CreateHullShader(Library, Hash); } FORCEINLINE FDomainShaderRHIRef RHICreateDomainShader(const TArray<uint8>& Code) { return FRHICommandListExecutor::GetImmediateCommandList().CreateDomainShader(Code); } FORCEINLINE FDomainShaderRHIRef RHICreateDomainShader(FRHIShaderLibraryParamRef Library, FSHAHash Hash) { return FRHICommandListExecutor::GetImmediateCommandList().CreateDomainShader(Library, Hash); } FORCEINLINE FGeometryShaderRHIRef RHICreateGeometryShader(const TArray<uint8>& Code) { return FRHICommandListExecutor::GetImmediateCommandList().CreateGeometryShader(Code); } FORCEINLINE FGeometryShaderRHIRef RHICreateGeometryShader(FRHIShaderLibraryParamRef Library, FSHAHash Hash) { return FRHICommandListExecutor::GetImmediateCommandList().CreateGeometryShader(Library, Hash); } FORCEINLINE FGeometryShaderRHIRef RHICreateGeometryShaderWithStreamOutput(const TArray<uint8>& Code, const FStreamOutElementList& ElementList, uint32 NumStrides, const uint32* Strides, int32 RasterizedStream) { return FRHICommandListExecutor::GetImmediateCommandList().CreateGeometryShaderWithStreamOutput(Code, ElementList, NumStrides, Strides, RasterizedStream); } FORCEINLINE FGeometryShaderRHIRef RHICreateGeometryShaderWithStreamOutput(const FStreamOutElementList& ElementList, uint32 NumStrides, const uint32* Strides, int32 RasterizedStream, FRHIShaderLibraryParamRef Library, FSHAHash Hash) { return FRHICommandListExecutor::GetImmediateCommandList().CreateGeometryShaderWithStreamOutput(ElementList, NumStrides, Strides, RasterizedStream, Library, Hash); } FORCEINLINE FComputeShaderRHIRef RHICreateComputeShader(const TArray<uint8>& Code) { return FRHICommandListExecutor::GetImmediateCommandList().CreateComputeShader(Code); } FORCEINLINE FComputeShaderRHIRef RHICreateComputeShader(FRHIShaderLibraryParamRef Library, FSHAHash Hash) { return FRHICommandListExecutor::GetImmediateCommandList().CreateComputeShader(Library, Hash); } FORCEINLINE FComputeFenceRHIRef RHICreateComputeFence(const FName& Name) { return FRHICommandListExecutor::GetImmediateCommandList().CreateComputeFence(Name); } FORCEINLINE FIndexBufferRHIRef RHICreateAndLockIndexBuffer(uint32 Stride, uint32 Size, uint32 InUsage, FRHIResourceCreateInfo& CreateInfo, void*& OutDataBuffer) { return FRHICommandListExecutor::GetImmediateCommandList().CreateAndLockIndexBuffer(Stride, Size, InUsage, CreateInfo, OutDataBuffer); } FORCEINLINE FIndexBufferRHIRef RHICreateIndexBuffer(uint32 Stride, uint32 Size, uint32 InUsage, FRHIResourceCreateInfo& CreateInfo) { return FRHICommandListExecutor::GetImmediateCommandList().CreateIndexBuffer(Stride, Size, InUsage, CreateInfo); } FORCEINLINE void* RHILockIndexBuffer(FIndexBufferRHIParamRef IndexBuffer, uint32 Offset, uint32 Size, EResourceLockMode LockMode) { return FRHICommandListExecutor::GetImmediateCommandList().LockIndexBuffer(IndexBuffer, Offset, Size, LockMode); } FORCEINLINE void RHIUnlockIndexBuffer(FIndexBufferRHIParamRef IndexBuffer) { FRHICommandListExecutor::GetImmediateCommandList().UnlockIndexBuffer(IndexBuffer); } FORCEINLINE FVertexBufferRHIRef RHICreateAndLockVertexBuffer(uint32 Size, uint32 InUsage, FRHIResourceCreateInfo& CreateInfo, void*& OutDataBuffer) { return FRHICommandListExecutor::GetImmediateCommandList().CreateAndLockVertexBuffer(Size, InUsage, CreateInfo, OutDataBuffer); } FORCEINLINE FVertexBufferRHIRef RHICreateVertexBuffer(uint32 Size, uint32 InUsage, FRHIResourceCreateInfo& CreateInfo) { return FRHICommandListExecutor::GetImmediateCommandList().CreateVertexBuffer(Size, InUsage, CreateInfo); } FORCEINLINE void* RHILockVertexBuffer(FVertexBufferRHIParamRef VertexBuffer, uint32 Offset, uint32 SizeRHI, EResourceLockMode LockMode) { return FRHICommandListExecutor::GetImmediateCommandList().LockVertexBuffer(VertexBuffer, Offset, SizeRHI, LockMode); } FORCEINLINE void RHIUnlockVertexBuffer(FVertexBufferRHIParamRef VertexBuffer) { FRHICommandListExecutor::GetImmediateCommandList().UnlockVertexBuffer(VertexBuffer); } FORCEINLINE FStructuredBufferRHIRef RHICreateStructuredBuffer(uint32 Stride, uint32 Size, uint32 InUsage, FRHIResourceCreateInfo& CreateInfo) { return FRHICommandListExecutor::GetImmediateCommandList().CreateStructuredBuffer(Stride, Size, InUsage, CreateInfo); } FORCEINLINE void* RHILockStructuredBuffer(FStructuredBufferRHIParamRef StructuredBuffer, uint32 Offset, uint32 SizeRHI, EResourceLockMode LockMode) { return FRHICommandListExecutor::GetImmediateCommandList().LockStructuredBuffer(StructuredBuffer, Offset, SizeRHI, LockMode); } FORCEINLINE void RHIUnlockStructuredBuffer(FStructuredBufferRHIParamRef StructuredBuffer) { FRHICommandListExecutor::GetImmediateCommandList().UnlockStructuredBuffer(StructuredBuffer); } FORCEINLINE FUnorderedAccessViewRHIRef RHICreateUnorderedAccessView(FStructuredBufferRHIParamRef StructuredBuffer, bool bUseUAVCounter, bool bAppendBuffer) { return FRHICommandListExecutor::GetImmediateCommandList().CreateUnorderedAccessView(StructuredBuffer, bUseUAVCounter, bAppendBuffer); } FORCEINLINE FUnorderedAccessViewRHIRef RHICreateUnorderedAccessView(FTextureRHIParamRef Texture, uint32 MipLevel = 0) { return FRHICommandListExecutor::GetImmediateCommandList().CreateUnorderedAccessView(Texture, MipLevel); } FORCEINLINE FUnorderedAccessViewRHIRef RHICreateUnorderedAccessView(FVertexBufferRHIParamRef VertexBuffer, uint8 Format) { return FRHICommandListExecutor::GetImmediateCommandList().CreateUnorderedAccessView(VertexBuffer, Format); } FORCEINLINE FShaderResourceViewRHIRef RHICreateShaderResourceView(FStructuredBufferRHIParamRef StructuredBuffer) { return FRHICommandListExecutor::GetImmediateCommandList().CreateShaderResourceView(StructuredBuffer); } FORCEINLINE FShaderResourceViewRHIRef RHICreateShaderResourceView(FVertexBufferRHIParamRef VertexBuffer, uint32 Stride, uint8 Format) { return FRHICommandListExecutor::GetImmediateCommandList().CreateShaderResourceView(VertexBuffer, Stride, Format); } FORCEINLINE FShaderResourceViewRHIRef RHICreateShaderResourceView(FIndexBufferRHIParamRef Buffer) { return FRHICommandListExecutor::GetImmediateCommandList().CreateShaderResourceView(Buffer); } FORCEINLINE FTextureReferenceRHIRef RHICreateTextureReference(FLastRenderTimeContainer* LastRenderTime) { return FRHICommandListExecutor::GetImmediateCommandList().CreateTextureReference(LastRenderTime); } FORCEINLINE void RHIUpdateTextureReference(FTextureReferenceRHIParamRef TextureRef, FTextureRHIParamRef NewTexture) { FRHICommandListExecutor::GetImmediateCommandList().UpdateTextureReference(TextureRef, NewTexture); } FORCEINLINE FTexture2DRHIRef RHICreateTexture2D(uint32 SizeX, uint32 SizeY, uint8 Format, uint32 NumMips, uint32 NumSamples, uint32 Flags, FRHIResourceCreateInfo& CreateInfo) { return FRHICommandListExecutor::GetImmediateCommandList().CreateTexture2D(SizeX, SizeY, Format, NumMips, NumSamples, Flags, CreateInfo); } FORCEINLINE FStructuredBufferRHIRef RHICreateRTWriteMaskBuffer(FTexture2DRHIRef RenderTarget) { return FRHICommandListExecutor::GetImmediateCommandList().CreateRTWriteMaskBuffer(RenderTarget); } FORCEINLINE FTexture2DRHIRef RHIAsyncCreateTexture2D(uint32 SizeX, uint32 SizeY, uint8 Format, uint32 NumMips, uint32 Flags, void** InitialMipData, uint32 NumInitialMips) { return FRHICommandListExecutor::GetImmediateCommandList().AsyncCreateTexture2D(SizeX, SizeY, Format, NumMips, Flags, InitialMipData, NumInitialMips); } FORCEINLINE void RHICopySharedMips(FTexture2DRHIParamRef DestTexture2D, FTexture2DRHIParamRef SrcTexture2D) { return FRHICommandListExecutor::GetImmediateCommandList().CopySharedMips(DestTexture2D, SrcTexture2D); } FORCEINLINE FTexture2DArrayRHIRef RHICreateTexture2DArray(uint32 SizeX, uint32 SizeY, uint32 SizeZ, uint8 Format, uint32 NumMips, uint32 Flags, FRHIResourceCreateInfo& CreateInfo) { return FRHICommandListExecutor::GetImmediateCommandList().CreateTexture2DArray(SizeX, SizeY, SizeZ, Format, NumMips, Flags, CreateInfo); } FORCEINLINE FTexture3DRHIRef RHICreateTexture3D(uint32 SizeX, uint32 SizeY, uint32 SizeZ, uint8 Format, uint32 NumMips, uint32 Flags, FRHIResourceCreateInfo& CreateInfo) { return FRHICommandListExecutor::GetImmediateCommandList().CreateTexture3D(SizeX, SizeY, SizeZ, Format, NumMips, Flags, CreateInfo); } FORCEINLINE FShaderResourceViewRHIRef RHICreateShaderResourceView(FTexture2DRHIParamRef Texture2DRHI, uint8 MipLevel) { return FRHICommandListExecutor::GetImmediateCommandList().CreateShaderResourceView(Texture2DRHI, MipLevel); } FORCEINLINE FShaderResourceViewRHIRef RHICreateShaderResourceView(FTexture2DRHIParamRef Texture2DRHI, uint8 MipLevel, uint8 NumMipLevels, uint8 Format) { return FRHICommandListExecutor::GetImmediateCommandList().CreateShaderResourceView(Texture2DRHI, MipLevel, NumMipLevels, Format); } FORCEINLINE FShaderResourceViewRHIRef RHICreateShaderResourceView(FTexture3DRHIParamRef Texture3DRHI, uint8 MipLevel) { return FRHICommandListExecutor::GetImmediateCommandList().CreateShaderResourceView(Texture3DRHI, MipLevel); } FORCEINLINE FShaderResourceViewRHIRef RHICreateShaderResourceView(FTexture2DArrayRHIParamRef Texture2DArrayRHI, uint8 MipLevel) { return FRHICommandListExecutor::GetImmediateCommandList().CreateShaderResourceView(Texture2DArrayRHI, MipLevel); } FORCEINLINE FShaderResourceViewRHIRef RHICreateShaderResourceView(FTextureCubeRHIParamRef TextureCubeRHI, uint8 MipLevel) { return FRHICommandListExecutor::GetImmediateCommandList().CreateShaderResourceView(TextureCubeRHI, MipLevel); } FORCEINLINE FTexture2DRHIRef RHIAsyncReallocateTexture2D(FTexture2DRHIParamRef Texture2D, int32 NewMipCount, int32 NewSizeX, int32 NewSizeY, FThreadSafeCounter* RequestStatus) { return FRHICommandListExecutor::GetImmediateCommandList().AsyncReallocateTexture2D(Texture2D, NewMipCount, NewSizeX, NewSizeY, RequestStatus); } FORCEINLINE ETextureReallocationStatus RHIFinalizeAsyncReallocateTexture2D(FTexture2DRHIParamRef Texture2D, bool bBlockUntilCompleted) { return FRHICommandListExecutor::GetImmediateCommandList().FinalizeAsyncReallocateTexture2D(Texture2D, bBlockUntilCompleted); } FORCEINLINE ETextureReallocationStatus RHICancelAsyncReallocateTexture2D(FTexture2DRHIParamRef Texture2D, bool bBlockUntilCompleted) { return FRHICommandListExecutor::GetImmediateCommandList().CancelAsyncReallocateTexture2D(Texture2D, bBlockUntilCompleted); } FORCEINLINE void* RHILockTexture2D(FTexture2DRHIParamRef Texture, uint32 MipIndex, EResourceLockMode LockMode, uint32& DestStride, bool bLockWithinMiptail, bool bFlushRHIThread = true) { return FRHICommandListExecutor::GetImmediateCommandList().LockTexture2D(Texture, MipIndex, LockMode, DestStride, bLockWithinMiptail, bFlushRHIThread); } FORCEINLINE void RHIUnlockTexture2D(FTexture2DRHIParamRef Texture, uint32 MipIndex, bool bLockWithinMiptail, bool bFlushRHIThread = true) { FRHICommandListExecutor::GetImmediateCommandList().UnlockTexture2D(Texture, MipIndex, bLockWithinMiptail, bFlushRHIThread); } FORCEINLINE void* RHILockTexture2DArray(FTexture2DArrayRHIParamRef Texture, uint32 TextureIndex, uint32 MipIndex, EResourceLockMode LockMode, uint32& DestStride, bool bLockWithinMiptail) { return FRHICommandListExecutor::GetImmediateCommandList().LockTexture2DArray(Texture, TextureIndex, MipIndex, LockMode, DestStride, bLockWithinMiptail); } FORCEINLINE void RHIUnlockTexture2DArray(FTexture2DArrayRHIParamRef Texture, uint32 TextureIndex, uint32 MipIndex, bool bLockWithinMiptail) { FRHICommandListExecutor::GetImmediateCommandList().UnlockTexture2DArray(Texture, TextureIndex, MipIndex, bLockWithinMiptail); } FORCEINLINE void RHIUpdateTexture2D(FTexture2DRHIParamRef Texture, uint32 MipIndex, const struct FUpdateTextureRegion2D& UpdateRegion, uint32 SourcePitch, const uint8* SourceData) { FRHICommandListExecutor::GetImmediateCommandList().UpdateTexture2D(Texture, MipIndex, UpdateRegion, SourcePitch, SourceData); } FORCEINLINE FUpdateTexture3DData RHIBeginUpdateTexture3D(FTexture3DRHIParamRef Texture, uint32 MipIndex, const struct FUpdateTextureRegion3D& UpdateRegion) { return FRHICommandListExecutor::GetImmediateCommandList().BeginUpdateTexture3D(Texture, MipIndex, UpdateRegion); } FORCEINLINE void RHIEndUpdateTexture3D(FUpdateTexture3DData& UpdateData) { FRHICommandListExecutor::GetImmediateCommandList().EndUpdateTexture3D(UpdateData); } FORCEINLINE void RHIUpdateTexture3D(FTexture3DRHIParamRef Texture, uint32 MipIndex, const struct FUpdateTextureRegion3D& UpdateRegion, uint32 SourceRowPitch, uint32 SourceDepthPitch, const uint8* SourceData) { FRHICommandListExecutor::GetImmediateCommandList().UpdateTexture3D(Texture, MipIndex, UpdateRegion, SourceRowPitch, SourceDepthPitch, SourceData); } FORCEINLINE FTextureCubeRHIRef RHICreateTextureCube(uint32 Size, uint8 Format, uint32 NumMips, uint32 Flags, FRHIResourceCreateInfo& CreateInfo) { return FRHICommandListExecutor::GetImmediateCommandList().CreateTextureCube(Size, Format, NumMips, Flags, CreateInfo); } FORCEINLINE FTextureCubeRHIRef RHICreateTextureCubeArray(uint32 Size, uint32 ArraySize, uint8 Format, uint32 NumMips, uint32 Flags, FRHIResourceCreateInfo& CreateInfo) { return FRHICommandListExecutor::GetImmediateCommandList().CreateTextureCubeArray(Size, ArraySize, Format, NumMips, Flags, CreateInfo); } FORCEINLINE void* RHILockTextureCubeFace(FTextureCubeRHIParamRef Texture, uint32 FaceIndex, uint32 ArrayIndex, uint32 MipIndex, EResourceLockMode LockMode, uint32& DestStride, bool bLockWithinMiptail) { return FRHICommandListExecutor::GetImmediateCommandList().LockTextureCubeFace(Texture, FaceIndex, ArrayIndex, MipIndex, LockMode, DestStride, bLockWithinMiptail); } FORCEINLINE void RHIUnlockTextureCubeFace(FTextureCubeRHIParamRef Texture, uint32 FaceIndex, uint32 ArrayIndex, uint32 MipIndex, bool bLockWithinMiptail) { FRHICommandListExecutor::GetImmediateCommandList().UnlockTextureCubeFace(Texture, FaceIndex, ArrayIndex, MipIndex, bLockWithinMiptail); } FORCEINLINE FRenderQueryRHIRef RHICreateRenderQuery(ERenderQueryType QueryType) { return FRHICommandListExecutor::GetImmediateCommandList().CreateRenderQuery(QueryType); } FORCEINLINE void RHIAcquireTransientResource(FTextureRHIParamRef Resource) { FRHICommandListExecutor::GetImmediateCommandList().AcquireTransientResource_RenderThread(Resource); } FORCEINLINE void RHIDiscardTransientResource(FTextureRHIParamRef Resource) { FRHICommandListExecutor::GetImmediateCommandList().DiscardTransientResource_RenderThread(Resource); } FORCEINLINE void RHIAcquireTransientResource(FVertexBufferRHIParamRef Resource) { FRHICommandListExecutor::GetImmediateCommandList().AcquireTransientResource_RenderThread(Resource); } FORCEINLINE void RHIDiscardTransientResource(FVertexBufferRHIParamRef Resource) { FRHICommandListExecutor::GetImmediateCommandList().DiscardTransientResource_RenderThread(Resource); } FORCEINLINE void RHIAcquireTransientResource(FStructuredBufferRHIParamRef Resource) { FRHICommandListExecutor::GetImmediateCommandList().AcquireTransientResource_RenderThread(Resource); } FORCEINLINE void RHIDiscardTransientResource(FStructuredBufferRHIParamRef Resource) { FRHICommandListExecutor::GetImmediateCommandList().DiscardTransientResource_RenderThread(Resource); } FORCEINLINE void RHIAcquireThreadOwnership() { return FRHICommandListExecutor::GetImmediateCommandList().AcquireThreadOwnership(); } FORCEINLINE void RHIReleaseThreadOwnership() { return FRHICommandListExecutor::GetImmediateCommandList().ReleaseThreadOwnership(); } FORCEINLINE void RHIFlushResources() { return FRHICommandListExecutor::GetImmediateCommandList().FlushResources(); } FORCEINLINE void RHIVirtualTextureSetFirstMipInMemory(FTexture2DRHIParamRef Texture, uint32 FirstMip) { FRHICommandListExecutor::GetImmediateCommandList().VirtualTextureSetFirstMipInMemory(Texture, FirstMip); } FORCEINLINE void RHIVirtualTextureSetFirstMipVisible(FTexture2DRHIParamRef Texture, uint32 FirstMip) { FRHICommandListExecutor::GetImmediateCommandList().VirtualTextureSetFirstMipVisible(Texture, FirstMip); } FORCEINLINE void RHIExecuteCommandList(FRHICommandList* CmdList) { FRHICommandListExecutor::GetImmediateCommandList().ExecuteCommandList(CmdList); } FORCEINLINE void* RHIGetNativeDevice() { return FRHICommandListExecutor::GetImmediateCommandList().GetNativeDevice(); } FORCEINLINE void RHIRecreateRecursiveBoundShaderStates() { FRHICommandListExecutor::GetImmediateCommandList(). ImmediateFlush(EImmediateFlushType::FlushRHIThread); GDynamicRHI->RHIRecreateRecursiveBoundShaderStates(); } FORCEINLINE FRHIShaderLibraryRef RHICreateShaderLibrary(EShaderPlatform Platform, FString FilePath) { return FRHICommandListExecutor::GetImmediateCommandList().CreateShaderLibrary(Platform, FilePath); } #include "RHICommandList.inl"
35.783677
332
0.816011
2d0c643b6b9db55eaaa5d471dd0399a6cae214d7
1,266
h
C
Arkanoid/Game/Objects/ALevel.h
Cellyceos/Arkanoid
de1466a0e1aa1f9f06f201826c5302943fb6385a
[ "MIT" ]
null
null
null
Arkanoid/Game/Objects/ALevel.h
Cellyceos/Arkanoid
de1466a0e1aa1f9f06f201826c5302943fb6385a
[ "MIT" ]
null
null
null
Arkanoid/Game/Objects/ALevel.h
Cellyceos/Arkanoid
de1466a0e1aa1f9f06f201826c5302943fb6385a
[ "MIT" ]
null
null
null
// // Level.h // Manages all objects at the level. // // Created by Kirill Bravichev on 02/28/2021. // Copyright (c) 2021 Cellyceos. All rights reserved. // #pragma once #include "AObject.h" #include "GameConfig.h" class ALevel : public AObject { public: ALevel(); virtual ~ALevel(); bool StartGame(int32 InLevel = 1); virtual void SetupPlayerInput(const TSharedPtr<class IInputHandler>& InputComponent) override; virtual void Update(float DeltaTime) override; virtual void Draw(const TSharedPtr<ARendererClass>& Renderer) const override; virtual void SetRect(const FRect& Rect) override; virtual int32 GetCurrentLevel() const { return Level; } virtual int32 GetLivesCount() const { return CurrentLives; } virtual int32 GetAliveBlocksCount() const { return AliveBlocksCount; } protected: TSharedPtr<class ABall> Ball; TSharedPtr<class APlatform> Platform; TFixedArray<TSharedPtr<class ABlock>, GameConfig::ColNum * GameConfig::RowNum> StaticObjects; void ReleaseBall(EInputState KeyEvent); private: int32 AliveBlocksCount{ 0 }; int32 CurrentLives{ 3 }; int32 Level{ 1 }; const FColor BorderColor{ 125, 125, 125, 255 }; const float BorderSize{ 5.0f }; void CheckCollision(); void ShouldBeInside(const TSharedPtr<AObject>&); };
23.886792
95
0.749605
2dfc209b79f48b944ff5a29acfe08b45140bfe45
462
c
C
Docs/C/C_signal/tmp_signal_2.c
turesnake/tprLearningNotes
cc25dbd108e3aff47f1d63b55591e6a5ea6f061d
[ "MIT" ]
null
null
null
Docs/C/C_signal/tmp_signal_2.c
turesnake/tprLearningNotes
cc25dbd108e3aff47f1d63b55591e6a5ea6f061d
[ "MIT" ]
null
null
null
Docs/C/C_signal/tmp_signal_2.c
turesnake/tprLearningNotes
cc25dbd108e3aff47f1d63b55591e6a5ea6f061d
[ "MIT" ]
null
null
null
//-- sleep 2 --- #include <setjmp.h> #include <signal.h> #include <unistd.h> static jmp_buf env_alrm; //-- jmp节点 static void sig_alrm( int signo ){ longjmp( env_alrm, 1 ); //-- 返回 1 } unsigned int sleep2( unsigned int seconds ){ if( signal(SIGALRM, sig_alrm) == SIG_ERR ){ return( seconds ); //-- signal 调用失败,退出 sleep1 函数。 } if( setjmp(env_alrm) == 0 ){ alarm( seconds ); pause(); } return( alarm(0) ); }
16.5
57
0.569264
f67a65fe15e787dd79b10988bb9ca52673319720
5,946
c
C
USB_Audio.cydsn/Interrupts.c
tndP5LP/USB_Audio_prj
c908c634250b8b16cfe2a214326555acbe09a031
[ "BSD-3-Clause" ]
null
null
null
USB_Audio.cydsn/Interrupts.c
tndP5LP/USB_Audio_prj
c908c634250b8b16cfe2a214326555acbe09a031
[ "BSD-3-Clause" ]
null
null
null
USB_Audio.cydsn/Interrupts.c
tndP5LP/USB_Audio_prj
c908c634250b8b16cfe2a214326555acbe09a031
[ "BSD-3-Clause" ]
null
null
null
/******************************************************************************* * File Name: Interrupts.c * * Version 1.0 * * Description: This file contains interrupt service routines for all the interrupts * in the system * ******************************************************************************* * Copyright (2015), Cypress Semiconductor Corporation. ******************************************************************************* * This software, including source code, documentation and related materials * ("Software") is owned by Cypress Semiconductor Corporation (Cypress) and is * protected by and subject to worldwide patent protection (United States and * foreign), United States copyright laws and international treaty provisions. * Cypress hereby grants to licensee a personal, non-exclusive, non-transferable * license to copy, use, modify, create derivative works of, and compile the * Cypress source code and derivative works for the sole purpose of creating * custom software in support of licensee product, such licensee product to be * used only in conjunction with Cypress's integrated circuit as specified in the * applicable agreement. Any reproduction, modification, translation, compilation, * or representation of this Software except as specified above is prohibited * without the express written permission of Cypress. * * Disclaimer: THIS SOFTWARE IS PROVIDED AS-IS, WITH NO WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, NONINFRINGEMENT, IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * Cypress reserves the right to make changes to the Software without notice. * Cypress does not assume any liability arising out of the application or use * of Software or any product or circuit described in the Software. Cypress does * not authorize its products for use as critical components in any products * where a malfunction or failure may reasonably be expected to result in * significant injury or death ("ACTIVE Risk Product"). By including Cypress's * product in a ACTIVE Risk Product, the manufacturer of such system or application * assumes all risk of such use and in doing so indemnifies Cypress against all * liability. Use of this Software may be limited by and subject to the applicable * Cypress software license agreement. *******************************************************************************/ #include <project.h> #if 0 extern uint16 inCnt; extern uint16 inLevel; extern uint16 inUsbCount; extern uint16 inUsbShadow; extern uint16 outLevel; extern uint16 outUsbCount; extern uint16 outUsbShadow; /******************************************************************************* * Function Name: InDMADone_Interrupt ******************************************************************************** * Summary: * The Interrupt Service Routine for isr_InDMADone. Arms USB Audio In end-point * for USB host to receive audio data. * * * Parameters: * InDMADone interrupt vector * * Return: * void. * *******************************************************************************/ CY_ISR(InDMADone_Interrupt) { /* Parameters to this API Call CHANGE DEPENDING ON DATA ENDPOINT MEMORY MODE */ USBFS_LoadInEP(AUDIO_IN_ENDPOINT, USBFS_NULL, inCnt); } /******************************************************************************* * Function Name: RxDMADone_Interrupt ******************************************************************************** * Summary: * The Interrupt Service Routine for isr_RxDMADone. This handles the AUDIO In * buffer pointers and detects overflow of the buffer to stop AUDIO In. * * Parameters: * RxDMADone interrupt vector * * Return: * void. * *******************************************************************************/ CY_ISR(RxDMADone_Interrupt) { uint16 removed; /* Note: Care must be taken in the application code to update inUsbCount atomically */ removed = inUsbCount - inUsbShadow; inLevel -= removed; inUsbShadow = inUsbCount; if (inLevel >= IN_BUFSIZE) { /* Overflow, so disable the DMA, disable the I2S data and tell the main task to reset all its structures */ Stop_I2S_Rx(); } else { inLevel += IN_TRANS_SIZE; } } /******************************************************************************* * Function Name: TxDMADone_Interrupt ******************************************************************************** * Summary: * The Interrupt Service Routine for isr_TxDMADone. This handles the AUDIO Out * buffer pointers and detects underflow of the buffer to stop AUDIO out. * * Parameters: * TxDMADone interrupt vector * * Return: * void. * *******************************************************************************/ CY_ISR(TxDMADone_Interrupt) { uint16 added; /* Note: Care must be taken in the application code to update outUsbCount atomically * Code is currently implemented with both updater of this value in interrupts that are * the same priority so the code will not execute at the same time, but the code * has been written so that this is not a requirement. */ added = outUsbCount - outUsbShadow; outLevel += added; outUsbShadow = outUsbCount; if (outLevel <= AUDIOMAXPKT) { /* Underflow, so disable the DMA, disable I2S TX and tell the main task to reset all its structures */ Stop_I2S_Tx(); } else { outLevel -= OUT_TRANS_SIZE; } if (outLevel > (OUT_BUFSIZE + MAX_AUDIO_SAMPLE_SIZE)) { /* Stop I2S till the overflow condition is present - this provides USB enough time to correct the overflow Disable the DMA, mute and tell the main task to reset all its structures Stop DMA */ Stop_I2S_Tx(); } } #endif /* #if 0 */ /* [] END OF FILE */
37.396226
112
0.596031
6e52a6319df6fc3d8635cd20231e50752e5248b9
6,302
c
C
tests-clar/diff/submodules.c
arthurschreiber/libgit2
353a90bedb6e679306f740fd0c1a08fc7934fbaa
[ "Apache-2.0" ]
null
null
null
tests-clar/diff/submodules.c
arthurschreiber/libgit2
353a90bedb6e679306f740fd0c1a08fc7934fbaa
[ "Apache-2.0" ]
null
null
null
tests-clar/diff/submodules.c
arthurschreiber/libgit2
353a90bedb6e679306f740fd0c1a08fc7934fbaa
[ "Apache-2.0" ]
null
null
null
#include "clar_libgit2.h" #include "repository.h" #include "posix.h" #include "../submodule/submodule_helpers.h" static git_repository *g_repo = NULL; static void setup_submodules(void) { g_repo = cl_git_sandbox_init("submodules"); cl_fixture_sandbox("testrepo.git"); rewrite_gitmodules(git_repository_workdir(g_repo)); p_rename("submodules/testrepo/.gitted", "submodules/testrepo/.git"); } static void setup_submodules2(void) { g_repo = cl_git_sandbox_init("submod2"); cl_fixture_sandbox("submod2_target"); p_rename("submod2_target/.gitted", "submod2_target/.git"); rewrite_gitmodules(git_repository_workdir(g_repo)); p_rename("submod2/not-submodule/.gitted", "submod2/not-submodule/.git"); p_rename("submod2/not/.gitted", "submod2/not/.git"); } void test_diff_submodules__initialize(void) { } void test_diff_submodules__cleanup(void) { cl_git_sandbox_cleanup(); cl_fixture_cleanup("testrepo.git"); cl_fixture_cleanup("submod2_target"); } static void check_diff_patches(git_diff_list *diff, const char **expected) { const git_diff_delta *delta; git_diff_patch *patch = NULL; size_t d, num_d = git_diff_num_deltas(diff); char *patch_text; for (d = 0; d < num_d; ++d, git_diff_patch_free(patch)) { cl_git_pass(git_diff_get_patch(&patch, &delta, diff, d)); if (delta->status == GIT_DELTA_UNMODIFIED) continue; if (expected[d] && !strcmp(expected[d], "<SKIP>")) continue; if (expected[d] && !strcmp(expected[d], "<END>")) cl_assert(0); cl_git_pass(git_diff_patch_to_str(&patch_text, patch)); cl_assert_equal_s(expected[d], patch_text); git__free(patch_text); } cl_assert(expected[d] && !strcmp(expected[d], "<END>")); } void test_diff_submodules__unmodified_submodule(void) { git_diff_options opts = GIT_DIFF_OPTIONS_INIT; git_diff_list *diff = NULL; static const char *expected[] = { "<SKIP>", /* .gitmodules */ NULL, /* added */ NULL, /* ignored */ "diff --git a/modified b/modified\nindex 092bfb9..452216e 100644\n--- a/modified\n+++ b/modified\n@@ -1 +1,2 @@\n-yo\n+changed\n+\n", /* modified */ NULL, /* testrepo.git */ NULL, /* unmodified */ NULL, /* untracked */ "<END>" }; setup_submodules(); opts.flags = GIT_DIFF_INCLUDE_IGNORED | GIT_DIFF_INCLUDE_UNTRACKED | GIT_DIFF_INCLUDE_UNMODIFIED; cl_git_pass(git_diff_index_to_workdir(&diff, g_repo, NULL, &opts)); check_diff_patches(diff, expected); git_diff_list_free(diff); } void test_diff_submodules__dirty_submodule(void) { git_diff_options opts = GIT_DIFF_OPTIONS_INIT; git_diff_list *diff = NULL; static const char *expected[] = { "<SKIP>", /* .gitmodules */ NULL, /* added */ NULL, /* ignored */ "diff --git a/modified b/modified\nindex 092bfb9..452216e 100644\n--- a/modified\n+++ b/modified\n@@ -1 +1,2 @@\n-yo\n+changed\n+\n", /* modified */ "diff --git a/testrepo b/testrepo\nindex a65fedf..a65fedf 160000\n--- a/testrepo\n+++ b/testrepo\n@@ -1 +1 @@\n-Subproject commit a65fedf39aefe402d3bb6e24df4d4f5fe4547750\n+Subproject commit a65fedf39aefe402d3bb6e24df4d4f5fe4547750-dirty\n", /* testrepo.git */ NULL, /* unmodified */ NULL, /* untracked */ "<END>" }; setup_submodules(); cl_git_rewritefile("submodules/testrepo/README", "heyheyhey"); cl_git_mkfile("submodules/testrepo/all_new.txt", "never seen before"); opts.flags = GIT_DIFF_INCLUDE_IGNORED | GIT_DIFF_INCLUDE_UNTRACKED | GIT_DIFF_INCLUDE_UNMODIFIED; cl_git_pass(git_diff_index_to_workdir(&diff, g_repo, NULL, &opts)); check_diff_patches(diff, expected); git_diff_list_free(diff); } void test_diff_submodules__submod2_index_to_wd(void) { git_diff_options opts = GIT_DIFF_OPTIONS_INIT; git_diff_list *diff = NULL; static const char *expected[] = { "<SKIP>", /* .gitmodules */ NULL, /* not-submodule */ NULL, /* not */ "diff --git a/sm_changed_file b/sm_changed_file\nindex 4800958..4800958 160000\n--- a/sm_changed_file\n+++ b/sm_changed_file\n@@ -1 +1 @@\n-Subproject commit 480095882d281ed676fe5b863569520e54a7d5c0\n+Subproject commit 480095882d281ed676fe5b863569520e54a7d5c0-dirty\n", /* sm_changed_file */ "diff --git a/sm_changed_head b/sm_changed_head\nindex 4800958..3d9386c 160000\n--- a/sm_changed_head\n+++ b/sm_changed_head\n@@ -1 +1 @@\n-Subproject commit 480095882d281ed676fe5b863569520e54a7d5c0\n+Subproject commit 3d9386c507f6b093471a3e324085657a3c2b4247\n", /* sm_changed_head */ "diff --git a/sm_changed_index b/sm_changed_index\nindex 4800958..4800958 160000\n--- a/sm_changed_index\n+++ b/sm_changed_index\n@@ -1 +1 @@\n-Subproject commit 480095882d281ed676fe5b863569520e54a7d5c0\n+Subproject commit 480095882d281ed676fe5b863569520e54a7d5c0-dirty\n", /* sm_changed_index */ "diff --git a/sm_changed_untracked_file b/sm_changed_untracked_file\nindex 4800958..4800958 160000\n--- a/sm_changed_untracked_file\n+++ b/sm_changed_untracked_file\n@@ -1 +1 @@\n-Subproject commit 480095882d281ed676fe5b863569520e54a7d5c0\n+Subproject commit 480095882d281ed676fe5b863569520e54a7d5c0-dirty\n", /* sm_changed_untracked_file */ "diff --git a/sm_missing_commits b/sm_missing_commits\nindex 4800958..5e49635 160000\n--- a/sm_missing_commits\n+++ b/sm_missing_commits\n@@ -1 +1 @@\n-Subproject commit 480095882d281ed676fe5b863569520e54a7d5c0\n+Subproject commit 5e4963595a9774b90524d35a807169049de8ccad\n", /* sm_missing_commits */ "<END>" }; setup_submodules2(); opts.flags = GIT_DIFF_INCLUDE_UNTRACKED; cl_git_pass(git_diff_index_to_workdir(&diff, g_repo, NULL, &opts)); check_diff_patches(diff, expected); git_diff_list_free(diff); } void test_diff_submodules__submod2_head_to_index(void) { git_diff_options opts = GIT_DIFF_OPTIONS_INIT; git_tree *head; git_diff_list *diff = NULL; static const char *expected[] = { "<SKIP>", /* .gitmodules */ "diff --git a/sm_added_and_uncommited b/sm_added_and_uncommited\nnew file mode 160000\nindex 0000000..4800958\n--- /dev/null\n+++ b/sm_added_and_uncommited\n@@ -0,0 +1 @@\n+Subproject commit 480095882d281ed676fe5b863569520e54a7d5c0\n", /* sm_added_and_uncommited */ "<END>" }; setup_submodules2(); cl_git_pass(git_repository_head_tree(&head, g_repo)); opts.flags = GIT_DIFF_INCLUDE_UNTRACKED; cl_git_pass(git_diff_tree_to_index(&diff, g_repo, head, NULL, &opts)); check_diff_patches(diff, expected); git_diff_list_free(diff); git_tree_free(head); }
37.070588
343
0.75246
dc5c39ce69d7a8db9f2fdf51d215f6592bc96fce
2,815
h
C
catkin_ws/src/eigen_stl_containers/include/eigen_stl_containers/eigen_stl_map_container.h
Camixxx/-noetic-pr2
9a2263bdb4a1b76c39ab5d62e7701baa2a117b7c
[ "MIT" ]
4
2020-12-15T06:54:31.000Z
2021-06-16T01:41:13.000Z
catkin_ws/src/eigen_stl_containers/include/eigen_stl_containers/eigen_stl_map_container.h
Camixxx/-noetic-pr2
9a2263bdb4a1b76c39ab5d62e7701baa2a117b7c
[ "MIT" ]
null
null
null
catkin_ws/src/eigen_stl_containers/include/eigen_stl_containers/eigen_stl_map_container.h
Camixxx/-noetic-pr2
9a2263bdb4a1b76c39ab5d62e7701baa2a117b7c
[ "MIT" ]
2
2021-01-25T03:54:51.000Z
2021-06-23T09:47:27.000Z
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan */ #ifndef EIGEN_STL_CONTAINERS_EIGEN_STL_MAP_CONTAINER_ #define EIGEN_STL_CONTAINERS_EIGEN_STL_MAP_CONTAINER_ #include <Eigen/Core> #include <Eigen/Geometry> #include <map> #include <string> #include <functional> namespace EigenSTL { typedef std::map<std::string, Eigen::Vector3d, std::less<std::string>, Eigen::aligned_allocator<std::pair<const std::string, Eigen::Vector3d> > > map_string_Vector3d; typedef std::map<std::string, Eigen::Vector3f, std::less<std::string>, Eigen::aligned_allocator<std::pair<const std::string, Eigen::Vector3f> > > map_string_Vector3f; typedef std::map<std::string, Eigen::Affine3d, std::less<std::string>, Eigen::aligned_allocator<std::pair<const std::string, Eigen::Affine3d> > > map_string_Affine3d; typedef std::map<std::string, Eigen::Affine3f, std::less<std::string>, Eigen::aligned_allocator<std::pair<const std::string, Eigen::Affine3f> > > map_string_Affine3f; } #endif
43.307692
112
0.69698
409ffc5fa74bd4f6a12b44acb0a3a498c6ccf6a5
24,083
h
C
Code/Libraries/UtilitiesDataTypes/Array3DUtils.h
NIRALUser/AtlasWerks
a074ca208ab41a6ed89c1f0b70004998f7397681
[ "BSD-3-Clause" ]
3
2016-04-26T05:06:06.000Z
2020-08-01T09:46:54.000Z
Code/Libraries/UtilitiesDataTypes/Array3DUtils.h
scalphunters/AtlasWerks
9d224bf8db628805368fcb7973ac578937b6b595
[ "BSD-3-Clause" ]
1
2018-11-27T21:53:48.000Z
2019-05-13T15:21:31.000Z
Code/Libraries/UtilitiesDataTypes/Array3DUtils.h
scalphunters/AtlasWerks
9d224bf8db628805368fcb7973ac578937b6b595
[ "BSD-3-Clause" ]
2
2019-01-24T02:07:17.000Z
2019-12-11T17:27:42.000Z
/* ================================================================ * * AtlasWerks Project * * Copyright (c) Sarang C. Joshi, Bradley C. Davis, J. Samuel Preston, * Linh K. Ha. All rights reserved. See Copyright.txt or for details. * * This software is distributed WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the above copyright notice for more information. * * ================================================================ */ #ifndef ARRAY3D_UTILS_H #define ARRAY3D_UTILS_H #ifndef SWIG #include <deque> #include <assert.h> #include <limits> #include "Vector3D.h" #include "Array3D.h" #include "DownsampleFilter3D.h" #include <algorithm> #include <limits> #include <string> #include <numeric> #include <vector> #include <iostream> #include <fstream> #include "ROI.h" #include "Timer.h" #include <typeinfo> #endif // SWIG #ifndef DEFAULT_INTERP_METHOD #define DEFAULT_INTERP_METHOD INTERP_LINEAR #endif // !DEFAULT_INTERP_METHOD // scoped version #define DEFAULT_SCALAR_INTERP Array3DUtils::DEFAULT_INTERP_METHOD #ifndef DEFAULT_BACKGROUND_STRATEGY #define DEFAULT_BACKGROUND_STRATEGY BACKGROUND_STRATEGY_VAL #endif // !DEFAULT_INTERP_METHOD // scoped version #define DEFAULT_SCALAR_BACKGROUND_STRATEGY Array3DUtils::DEFAULT_BACKGROUND_STRATEGY class Array3DUtils { public: /** * Strategies for functions that do trilinear interpolation -- what * to do if the value falls outside the image region. */ enum ScalarBackgroundStrategyT { BACKGROUND_STRATEGY_CLAMP, /// Clamp to the closest pixel value BACKGROUND_STRATEGY_WRAP, /// Wrap around the image BACKGROUND_STRATEGY_VAL /// Use a background value, zero if not specified }; /** * selection of interpolation strategy */ enum InterpT {INTERP_NN, INTERP_LINEAR, INTERP_CUBIC}; /** * Compile-time choice of interp method and background strategy */ template <class T, ScalarBackgroundStrategyT BackgroundStrategy, InterpT InterpMethod> static inline T interp(const Array3D<T>& array, const double& x, const double& y, const double& z, const T& background=(T)0.0) { if(InterpMethod == INTERP_NN){ return Array3DUtils::nearestNeighbor(array, x, y, z, background); }else if(InterpMethod == INTERP_LINEAR){ return Array3DUtils::trilerp<T, BackgroundStrategy>(array, x, y, z, background); }else if(InterpMethod == INTERP_CUBIC){ return Array3DUtils::cubicSplineinterp<T, BackgroundStrategy>(array, x, y, z, background); } }; template <class T> static inline T interp(const Array3D<T>& array, const double& x, const double& y, const double& z, const T& background=(T)0.0) { return interp<T, DEFAULT_BACKGROUND_STRATEGY, DEFAULT_INTERP_METHOD>(array, x, y, z, background); }; template <class T, ScalarBackgroundStrategyT BackgroundStrategy, InterpT InterpMethod> static inline T interp(const Array3D<T>& array, const Vector3D<double>& index, const T& background=(T)0.0) { return interp<T, BackgroundStrategy, InterpMethod>(array, index.x, index.y, index.z, background); }; template<class T> static inline T interp(const Array3D<T>& array, const Vector3D<double>& index, const T& background=(T)0.0) { return interp<T, DEFAULT_BACKGROUND_STRATEGY, DEFAULT_INTERP_METHOD>(array, index.x, index.y, index.z, background); }; /** * return array(round(x,y,z)) * if round(x,y,z) falls outside array, return background * * bcd 2003 */ template <class T> static T nearestNeighbor(const Array3D<T>& array, const double& x, const double& y, const double& z, const T& background); template <class T> static T nearestNeighbor(const Array3D<T>& array, const Vector3D<double>& index, const T& background); #ifdef SWIG %template(nearestNeighbor) nearestNeighbor< float >; %template(nearestNeighbor) nearestNeighbor< Vector3D< float > >; #endif // SWIG /** * trilinear interpolation into array at position x,y,z * * value is interpolated from corners of the cube... * * ^ * | v3 v2 -z-> v4 v5 * y --next slice--> * | v0 v1 v7 v6 * * -x-> * * where v0 is floor(x), floor(y), floor(z) * and v5 is floor(x)+1, floor(y)+1, floor(z)+1 * and so on. * * if any corner of the cube is outside of the volume, that corner * is set to background before performing the interpolation. If * background is set to numeric_limits<T>::max(), then clamping * is performed. * * * a fair amount of optimization work has gone into this function * * bcd 2003 */ template <class T, ScalarBackgroundStrategyT BackgroundStrategy> static T trilerp(const Array3D<T>& array, const double& x, const double& y, const double& z, const T& background = 0.0F); template <class T> static T trilerp(const Array3D<T>& array, const double& x, const double& y, const double& z, const T& background = 0.0F) { return trilerp<T, DEFAULT_SCALAR_BACKGROUND_STRATEGY>(array, x, y, z, background); } template <class T, ScalarBackgroundStrategyT BackgroundStrategy> static T trilerp(const Array3D<T>& array, const Vector3D<double>& position, const T& background=0.0F); template <class T> static T trilerp(const Array3D<T>& array, const Vector3D<double>& position, const T& background=0.0F) { return trilerp<T, DEFAULT_SCALAR_BACKGROUND_STRATEGY>(array, position, background); } #ifdef SWIG %template(trilerp) trilerp< float, DEFAULT_SCALAR_BACKGROUND_STRATEGY >; #endif // SWIG template <class T, ScalarBackgroundStrategyT BackgroundStrategy> static T cubicSplineinterp(const Array3D<T>& array, const Vector3D<double>& position, const T& background); template <class T, ScalarBackgroundStrategyT BackgroundStrategy> static T cubicSplineinterp(const Array3D<T>& array, const double& x, const double& y, const double& z, const T& background = 0.0F); template <class T> static T cubicsplineinterp(T*,double t,double u,double v); /** ------------------------------------------------------------------------ * Trilinear interpolation split into two functions. The first * computes 8 indices into an array and corresponding coefficients. * The second simply applies them. This makes sense if you have to * trilerp the same location in several images. */ template <class T> static bool computeTrilerpCoeffs(const Array3D<T>& array, const double& x, const double& y, const double& z, size_t& i0, size_t& i1, size_t& i2, size_t& i3, size_t& i4, size_t& i5, size_t& i6, size_t& i7, double& a0, double& a1, double& a2, double& a3, double& a4, double& a5, double& a6, double& a7); #ifdef SWIG %template(computeTrilerpCoeffs) computeTrilerpCoeffs< float >; #endif // SWIG // If the appropriate trilinear interpolation coefficients and // integer indices have been computed, apply them to a given array3D template <class T> static T weightedSumOfArrayValues( const Array3D<T>& array, const size_t& i0, const size_t& i1, const size_t& i2, const size_t& i3, const size_t& i4, const size_t& i5, const size_t& i6, const size_t& i7, const double& a0, const double& a1, const double& a2, const double& a3, const double& a4, const double& a5, const double& a6, const double& a7); #ifdef SWIG %template(weightedSumOfArrayValues) weightedSumOfArrayValues< float >; #endif // SWIG template <class T> static void extractROI(const Array3D<T>& array, Array3D<T>& roi, const Vector3D<int>& roiStart, const Vector3D<unsigned int>& roiSize); template <class T> static void extractROI(const Array3D<T>& array, Array3D<T>& roiArray, const ROI<int, unsigned int>& roi); #ifdef SWIG %template(extractROI) extractROI< float >; %template(extractROI) extractROI< Vector3D< float > >; #endif // SWIG /** * fill a region with a given value * * foskey 2005 */ template <class T> static void fillRegion(Array3D<T>& array, const ROI<int, unsigned int>& roi, const T& value); #ifdef SWIG %template(fillRegion) fillRegion< float >; %template(fillRegion) fillRegion< Vector3D< float > >; #endif // SWIG /** * copy a region from one Array3D<T> to another of the same type. * the region is specified by an origin and extent(size), these are * specified in array index coordinates. * * bcd 2003 */ template <class T> static void copyRegion(const Array3D<T>& inArray, Array3D<T>& outArray, const typename Array3D<T>::IndexType& inOrigin, const typename Array3D<T>::IndexType& outOrigin, const typename Array3D<T>::SizeType& regionSize); #ifdef SWIG %template(copyRegion) copyRegion< float >; %template(copyRegion) copyRegion< Vector3D< float > >; #endif // SWIG /** * copy a region from one Array3D<T> to another of type U. each * element is cast from type T to type U. the region is specified * by an origin and extent(size), these are specified in array index * coordinates. * * bcd 2003 */ template <class T, class U> static void copyRegionCast(const Array3D<T>& inArray, Array3D<U>& outArray, const typename Array3D<T>::IndexType& inOrigin, const typename Array3D<U>::IndexType& outOrigin, const typename Array3D<T>::SizeType& regionSize); #ifdef SWIG // since SWIG only supports float arrays, no casting really makes sense #endif // SWIG template <class T, class U> static void copyCast(const Array3D<T>& inArray, Array3D<U>& outArray); #ifdef SWIG // since SWIG only supports float arrays, no casting really makes sense #endif // SWIG /** * copy a region from one Array3D<T> to another of type U. each * element is rounded to the nearest integer and then cast to type * U. the region is specified by an origin and extent(size), these * are specified in array index coordinates. * * bcd 2003 */ template <class T, class U> static void copyRegionRound(const Array3D<T>& inArray, Array3D<U>& outArray, const typename Array3D<T>::IndexType& inOrigin, const typename Array3D<U>::IndexType& outOrigin, const typename Array3D<T>::SizeType& regionSize); #ifdef SWIG %template(copyRegionRound) copyRegionRound< float, float >; #endif // SWIG /** * compute the centroid of a region in an image. the centroid is * based on the origin of the array, not the origin of the region of * interest. * * bcd/lorenzen 2003 */ template <class T> static Vector3D<double> computeCentroid(const Array3D<T>& array, const typename Array3D<T>::IndexType& origin, const typename Array3D<T>::SizeType& size); #ifdef SWIG %template(computeCentroid) computeCentroid< float >; #endif // SWIG /** * a cheap way to downsample an image. * * if n is the downsampleFactor, take every nth element of an * Array3D in each dimension (starting with the 0th element), * producing an Array3D of size max(floor((x,y,z)/n, 1) * * bcd 2003 */ template <class T> static void downsampleByInt(const Array3D<T>& input, Array3D<T>& output, unsigned int downsampleFactor); #ifdef SWIG %template(downsampleByInt) downsampleByInt< float >; #endif // SWIG /** * a cheap way to downsample an image. * * if n is the downsampleFactor, take every nth element of an * Array3D in each dimension (starting with the 0th element), * producing an Array3D of size max(floor((x,y,z)/n, 1) * * bcd 2003 */ template <class T> static void downsampleByInts(const Array3D<T>& input, Array3D<T>& output, const Vector3D<unsigned int>& downsampleFactors); #ifdef SWIG %template(downsampleByInts) downsampleByInts< float >; #endif // SWIG template <class T> static void downsampleByTwo(const Array3D<T>& input, Array3D<T>& output); #ifdef SWIG %template(downsampleByTwo) downsampleByTwo< float >; #endif // SWIG /** * output can be the same array as input * * jsp 2010 */ template <class T> static void gaussianBlur (const Array3D<T>& input, Array3D<T>& output, const Vector3D<double>& sigma, const Vector3D<int>& kernelSize); #ifdef SWIG %template(gaussianBlur) gaussianBlur< float >; #endif // SWIG /** * output can be the same array as input * * prigent 2004 */ template <class T> static void gaussianDownsample (const Array3D<T>& input, Array3D<T>& output, const Vector3D<int>& factors, const Vector3D<double>& sigma, const Vector3D<int>& kernelSize); #ifdef SWIG %template(gaussianDownsample) gaussianDownsample< float >; #endif // SWIG /** * compute the gradient of an Array3D * * symmetric difference is used except on the boundaries where * foreward and reverse difference are used. If 'wrap' is true, * use wrapped symmetric differences throughout * * pjl 2004 (jdh 2008) */ template <class T, class U> static void computeGradient(const Array3D<T>& array, Array3D<Vector3D<U> >& grad, Vector3D<double> spacing = Vector3D<double>(1.0,1.0,1.0), bool wrap=false); #ifdef SWIG %template(computeGradient) computeGradient< float, float >; #endif // SWIG /** * * compute the laplacian of an Array3D * * * dp 2004 */ template <class T, class U> static void computeLaplacian(const Array3D<Vector3D<T> >& array, Array3D<Vector3D<U> >& laplacian); #ifdef SWIG %template(computeLaplacian) computeLaplacian< float, float >; #endif // SWIG /** * return the elementwise squared difference between two arrays * * sum (a1(x) - a2(x))^2 * x * * bcd 2003 */ template <class T> static T squaredDifference(const Array3D<T>& array1, const Array3D<T>& array2); #ifdef SWIG %template(squaredDifference) squaredDifference< float >; #endif // SWIG /** * compute the minimum and maximum values in an array * * if array is of size zero, min/max are not changed * * bcd 2003 * * Note: Do not change the names MIN_OUTPUT, MAX_OUTPUT -- these * are used by SWIG for generating python wrapping. The python * function operates as: * min, max = getMinMax(array) */ template <class T> static void getMinMax(const Array3D<T>& array, T& MIN_OUTPUT, T& MAX_OUTPUT); #ifdef SWIG %template(getMinMax) getMinMax< float >; #endif // SWIG /** * compute the elementwise arithmetic mean of a group of Array3Ds * * avg(x) = 1/numArrays * sum arrays[i](x) * numArrays * * avg must be initialized to the proper size prior to this function * call * * bcd 2003 */ template <class T> static void arithmeticMean(unsigned int numArrays, const Array3D<T>* const* arrays, Array3D<T>& avg); #ifdef SWIG %template(arithmeticMean) arithmeticMean< float >; #endif // SWIG /** * compute the elementwise sum of a group of Array3Ds * * sum(x) = sum arrays[i](x) * numArrays * * sum must be initialized to the proper size prior to this function * call * * */ template <class T> static void arithmeticSum(unsigned int numArrays, const Array3D<T>* const* arrays, Array3D<T>& sum); #ifdef SWIG %template(arithmeticSum) arithmeticSum< float >; #endif // SWIG /** * Sum all elements in array. * * jsp 2009 */ template <class T> static T sumElements(const Array3D<T>& inArray); #ifdef SWIG %template(sumElements) sumElements< float >; %template(sumElements) sumElements< Vector3D< float > >; #endif // SWIG /** * compute the elementwise arithmetic mean of a group of Array3Ds * * avg(x) = 1/numArrays * sum arrays[i](x) * numArrays * * avg must be initialized to the proper size prior to this function * call * * bcd 2003 */ template <class T> static void weightedArithmeticMean(unsigned int numArrays, const Array3D<T>** const arrays, const double* weights, Array3D<T>& avg); #ifdef SWIG %template(weightedArithmeticMean) weightedArithmeticMean< float >; #endif // SWIG /** * compute the elementwise sample variance of a group of Array3Ds * * var must be initialized to the proper size prior to this function * call * * bcd 2006 */ template <class T> static void sampleVariance(unsigned int numArrays, const Array3D<T>** const arrays, Array3D<T>& var); #ifdef SWIG %template(sampleVariance) sampleVariance< float >; #endif // SWIG /** * compute the elementwise trimmed arithmetic mean of a group of * Array3Ds, choose reasonable trim parameters * * avg must be initialized to the proper size prior to this function * call * * bcd 2004 */ template <class T> static void trimmedMean(unsigned int numArrays, const Array3D<T>** const arrays, Array3D<T>& avg); /** * compute the elementwise trimmed arithmetic mean of a group of * Array3Ds * * avg must be initialized to the proper size prior to this function * call * * bcd 2004 */ template <class T> static void trimmedMean(unsigned int numArrays, const Array3D<T>** const arrays, Array3D<T>& avg, unsigned int numTrimLeft, unsigned int numTrimRight); #ifdef SWIG %template(trimmedMean) trimmedMean< float >; #endif // SWIG /** * recompute the elementwise arithmetic mean of a group of Array3Ds * replacing one Array3D from the original mean computation with * another * * this just saves time over recomputing the mean from all arrays * * bcd 2003 */ template <class T> static void updateArithmeticMean(unsigned int numArrays, const Array3D<T>& oldInput, const Array3D<T>& newInput, Array3D<T>& avg); #ifdef SWIG %template(updateArithmeticMean) updateArithmeticMean< float >; #endif // SWIG /** * each element gets min of itself and its neighbors in x * * bcd 2004 */ template <class T> static void minFilter1DX(Array3D<T>& array); #ifdef SWIG %template(minFilter1DX) minFilter1DX< float >; #endif // SWIG /** * each element gets min of itself and its neighbors in y * * bcd 2004 */ template <class T> static void minFilter1DY(Array3D<T>& array); #ifdef SWIG %template(minFilter1DY) minFilter1DY< float >; #endif // SWIG /** * each element gets min of itself and its neighbors in z * * bcd 2004 */ template <class T> static void minFilter1DZ(Array3D<T>& array); #ifdef SWIG %template(minFilter1DZ) minFilter1DZ< float >; #endif // SWIG /** * each element gets min of itself and its neighbors 26 neighbors * * bcd 2004 */ template <class T> static void minFilter3D(Array3D<T>& array); #ifdef SWIG %template(minFilter3D) minFilter3D< float >; #endif // SWIG /** * each element gets max of itself and its neighbors in x * * bcd 2004 */ template <class T> static void maxFilter1DX(Array3D<T>& array); #ifdef SWIG %template(maxFilter1DX) maxFilter1DX< float >; #endif // SWIG /** * each element gets max of itself and its neighbors in y * * bcd 2004 */ template <class T> static void maxFilter1DY(Array3D<T>& array); #ifdef SWIG %template(maxFilter1DY) maxFilter1DY< float >; #endif // SWIG /** * each element gets max of itself and its neighbors in z * * bcd 2004 */ template <class T> static void maxFilter1DZ(Array3D<T>& array); #ifdef SWIG %template(maxFilter1DZ) maxFilter1DZ< float >; #endif // SWIG /** * each element gets max of itself and its neighbors 26 neighbors * * bcd 2004 */ template <class T> static void maxFilter3D(Array3D<T>& array); #ifdef SWIG %template(maxFilter3D) maxFilter3D< float >; #endif // SWIG template <class T> static void rescaleElements(Array3D<T>& array, const T& minValueOut, const T& maxValueOut); template <class T> static void rescaleElements(Array3D<T>& array, const T& minThreshold, const T& maxThreshold, const T& minValueOut, const T& maxValueOut); #ifdef SWIG %template(rescaleElements) rescaleElements< float >; #endif // SWIG template <class T> static void diffuse1DX(Array3D<T>& array); #ifdef SWIG %template(diffuse1DX) diffuse1DX< float >; #endif // SWIG template <class T> static void diffuse1DY(Array3D<T>& array); #ifdef SWIG %template(diffuse1DY) diffuse1DY< float >; #endif // SWIG template <class T> static void diffuse1DZ(Array3D<T>& array); #ifdef SWIG %template(diffuse1DZ) diffuse1DZ< float >; #endif // SWIG template <class T> static void diffuse3D(Array3D<T>& array); #ifdef SWIG %template(diffuse3D) diffuse3D< float >; #endif // SWIG template <class T, class U> static void select(const Array3D<T>& source, Array3D<T>& dest, const Array3D<U>& mask, const U& maskMin, const U& maskMax); #ifdef SWIG %template(select) select< float, float >; #endif // SWIG template <class T> static void refineZ(Array3D<T>& array, const double& newToOldSlicesRatio); #ifdef SWIG %template(refineZ) refineZ< float >; #endif // SWIG template <class T> static void flipX(Array3D<T>& array); #ifdef SWIG %template(flipX) flipX< float >; %template(flipX) flipX< Vector3D< float > >; #endif // SWIG template <class T> static void flipY(Array3D<T>& array); #ifdef SWIG %template(flipY) flipY< float >; %template(flipY) flipY< Vector3D< float > >; #endif // SWIG template <class T> static void flipZ(Array3D<T>& array); #ifdef SWIG %template(flipZ) flipZ< float >; %template(flipZ) flipZ< Vector3D< float > >; #endif // SWIG // Computes the mass of the array template <class T> static T mass(const Array3D<T>& array); #ifdef SWIG %template(mass) mass< float >; #endif // SWIG // Computes the mass of the array template <class T> static T sumOfSquaredElements(const Array3D<T>& array); #ifdef SWIG %template(sumOfSquaredElements) sumOfSquaredElements< float >; #endif // SWIG /** * adds the contents of b, componentwise, to a * the arrays must be of the same dimensions */ template <class T> static void sum(Array3D<T>& a, const Array3D<T>& b); #ifdef SWIG %template(sum) sum< float >; #endif // SWIG /** * Floodfill the region contiguous with 'seed' bounded by voxels * less than minThresh and higher than maxThresh */ template< class T > static void maskRegionDeterminedByThresholds(Array3D<T>& array, Array3D<unsigned char>& mask, const Vector3D<unsigned int>& seed, const T& minThresh, const T& maxThresh); #ifdef SWIG %template(maskRegionDeterminedByThresholds) maskRegionDeterminedByThresholds< float >; #endif // SWIG }; // class Array3DUtils #ifndef SWIG #include "Array3DUtils.txx" #endif // SWIG #endif
25.32387
119
0.643815
bcea25c7168af20d3ede0af09df101a50ffaa234
956
c
C
baekjoon/6203/source.c
qilip/ACMStudy
c4d6f31b01358ead4959c92f1fac59a3826f3f77
[ "CC-BY-3.0" ]
4
2020-02-02T08:34:46.000Z
2021-10-01T11:21:17.000Z
baekjoon/6203/source.c
qilip/ACMStudy
c4d6f31b01358ead4959c92f1fac59a3826f3f77
[ "CC-BY-3.0" ]
1
2021-09-04T14:03:50.000Z
2021-09-04T14:03:50.000Z
baekjoon/6203/source.c
qilip/ACMStudy
c4d6f31b01358ead4959c92f1fac59a3826f3f77
[ "CC-BY-3.0" ]
null
null
null
#include <stdio.h> int dist[1010][1010]; int n, x[1010], y[1010]; int main(void){ scanf("%d", &n); for(int i=0;i<n;i++){ scanf("%d %d", &x[i], &y[i]); } for(int i=0;i<n;i++){ for(int j=i+1;j<n;j++){ dist[i][j] = dist[j][i] = (x[j]-x[i])*(x[j]-x[i]) + (y[j]-y[i])*(y[j]-y[i]); } } int cant[1010] = {0}; int cur = 0; int cnt = n; while(cnt>1){ if(!cant[cur]){ int mind = 999999999; int mi = 0; for(int i=0;i<n;i++){ if(cant[i] || i==cur) continue; if(mind > dist[cur][i]){ mind = dist[cur][i]; mi = i; } } cnt--; cant[mi] = 1; } cur++; if(cur==n) cur = 0; } for(int i=0;i<n;i++){ if(!cant[i]){ printf("%d", i+1); break; } } return 0; }
21.727273
88
0.334728
56154055c44dc10f112c057e68e61388f9e67630
4,394
h
C
lldb/source/Plugins/SymbolFile/DWARF/DWARFDIE.h
zhongwuzw/llvm-project
19e1b0b2057e7ae59adebed84a1e8015148683fc
[ "Apache-2.0" ]
null
null
null
lldb/source/Plugins/SymbolFile/DWARF/DWARFDIE.h
zhongwuzw/llvm-project
19e1b0b2057e7ae59adebed84a1e8015148683fc
[ "Apache-2.0" ]
null
null
null
lldb/source/Plugins/SymbolFile/DWARF/DWARFDIE.h
zhongwuzw/llvm-project
19e1b0b2057e7ae59adebed84a1e8015148683fc
[ "Apache-2.0" ]
null
null
null
//===-- DWARFDIE.h ----------------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef LLDB_SOURCE_PLUGINS_SYMBOLFILE_DWARF_DWARFDIE_H #define LLDB_SOURCE_PLUGINS_SYMBOLFILE_DWARF_DWARFDIE_H #include "DWARFBaseDIE.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/iterator_range.h" class DWARFDIE : public DWARFBaseDIE { public: class child_iterator; using DWARFBaseDIE::DWARFBaseDIE; // Tests bool IsStructUnionOrClass() const; bool IsMethod() const; // Accessors // Accessing information about a DIE const char *GetMangledName() const; const char *GetPubname() const; const char *GetQualifiedName(std::string &storage) const; using DWARFBaseDIE::GetName; void GetName(lldb_private::Stream &s) const; void AppendTypeName(lldb_private::Stream &s) const; lldb_private::Type *ResolveType() const; // Resolve a type by UID using this DIE's DWARF file lldb_private::Type *ResolveTypeUID(const DWARFDIE &die) const; // Functions for obtaining DIE relations and references DWARFDIE GetParent() const; DWARFDIE GetFirstChild() const; DWARFDIE GetSibling() const; DWARFDIE GetReferencedDIE(const dw_attr_t attr) const; // Get a another DIE from the same DWARF file as this DIE. This will // check the current DIE's compile unit first to see if "die_offset" is // in the same compile unit, and fall back to checking the DWARF file. DWARFDIE GetDIE(dw_offset_t die_offset) const; using DWARFBaseDIE::GetDIE; DWARFDIE LookupDeepestBlock(lldb::addr_t file_addr) const; DWARFDIE GetParentDeclContextDIE() const; // DeclContext related functions std::vector<DWARFDIE> GetDeclContextDIEs() const; /// Return this DIE's decl context as it is needed to look up types /// in Clang's -gmodules debug info format. void GetDeclContext( llvm::SmallVectorImpl<lldb_private::CompilerContext> &context) const; // Getting attribute values from the DIE. // // GetAttributeValueAsXXX() functions should only be used if you are // looking for one or two attributes on a DIE. If you are trying to // parse all attributes, use GetAttributes (...) instead DWARFDIE GetAttributeValueAsReferenceDIE(const dw_attr_t attr) const; bool GetDIENamesAndRanges(const char *&name, const char *&mangled, DWARFRangeList &ranges, int &decl_file, int &decl_line, int &decl_column, int &call_file, int &call_line, int &call_column, lldb_private::DWARFExpression *frame_base) const; /// The range of all the children of this DIE. /// /// This is a template just because child_iterator is not completely defined /// at this point. template <typename T = child_iterator> llvm::iterator_range<T> children() const { return llvm::make_range(T(*this), T()); } }; class DWARFDIE::child_iterator : public llvm::iterator_facade_base<DWARFDIE::child_iterator, std::forward_iterator_tag, DWARFDIE> { /// The current child or an invalid DWARFDie. DWARFDIE m_die; public: child_iterator() = default; child_iterator(const DWARFDIE &parent) : m_die(parent.GetFirstChild()) {} bool operator==(const child_iterator &it) const { // DWARFDIE's operator== differentiates between an invalid DWARFDIE that // has a CU but no DIE and one that has neither CU nor DIE. The 'end' // iterator could be default constructed, so explicitly allow // (CU, (DIE)nullptr) == (nullptr, nullptr) -> true if (!m_die.IsValid() && !it.m_die.IsValid()) return true; return m_die == it.m_die; } const DWARFDIE &operator*() const { assert(m_die.IsValid() && "Derefencing invalid iterator?"); return m_die; } DWARFDIE &operator*() { assert(m_die.IsValid() && "Derefencing invalid iterator?"); return m_die; } child_iterator &operator++() { assert(m_die.IsValid() && "Incrementing invalid iterator?"); m_die = m_die.GetSibling(); return *this; } }; #endif // LLDB_SOURCE_PLUGINS_SYMBOLFILE_DWARF_DWARFDIE_H
32.072993
80
0.678425
f44b4b111aa6d395d5cd0b187837349f962e28ae
2,252
h
C
bistro/worker/test/FakeBistroWorkerThread.h
fakeNetflix/facebook-repo-bistro
68a9f5b158d37155d28f5dc914aed475e4c69fc0
[ "MIT" ]
null
null
null
bistro/worker/test/FakeBistroWorkerThread.h
fakeNetflix/facebook-repo-bistro
68a9f5b158d37155d28f5dc914aed475e4c69fc0
[ "MIT" ]
null
null
null
bistro/worker/test/FakeBistroWorkerThread.h
fakeNetflix/facebook-repo-bistro
68a9f5b158d37155d28f5dc914aed475e4c69fc0
[ "MIT" ]
null
null
null
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the LICENSE * file in the root directory of this source tree. */ #pragma once #include <thrift/lib/cpp2/util/ScopedServerInterfaceThread.h> #include "bistro/bistro/if/gen-cpp2/BistroWorker.h" namespace facebook { namespace bistro { struct FakeBistroWorker : public virtual cpp2::BistroWorkerSvIf { using TaskSubprocessOptsCob = std::function< void(const cpp2::RunningTask&, const cpp2::TaskSubprocessOptions& )>; // Needs RunningTask to detect healthchecks explicit FakeBistroWorker(TaskSubprocessOptsCob tso_cob) : taskSubprocessOptsCob_(std::move(tso_cob)) {} ~FakeBistroWorker() override {} void async_tm_runTask( std::unique_ptr<apache::thrift::HandlerCallback<void>> cb, const cpp2::RunningTask& rt, const std::string& config, const std::vector<std::string>& command, const cpp2::BistroInstanceID& scheduler, const cpp2::BistroInstanceID& worker, int64_t notify_if_tasks_not_running_sequence_num, const cpp2::TaskSubprocessOptions& ) override; void async_tm_getRunningTasks( std::unique_ptr< apache::thrift::HandlerCallback<std::vector<cpp2::RunningTask>>> cb, const cpp2::BistroInstanceID& worker ) override; TaskSubprocessOptsCob taskSubprocessOptsCob_; }; namespace detail { struct NoOpTaskSubprocessOptsCob { void operator()( const cpp2::RunningTask&, const cpp2::TaskSubprocessOptions& ) {} }; } // namespace detail class FakeBistroWorkerThread { public: using CustomizeWorkerCob = std::function<void(cpp2::BistroWorker*)>; explicit FakeBistroWorkerThread( std::string shard, CustomizeWorkerCob customize_worker_cob, FakeBistroWorker::TaskSubprocessOptsCob tso_cob = detail::NoOpTaskSubprocessOptsCob() ) : shard_(std::move(shard)), customizeWorkerCob_(std::move(customize_worker_cob)), ssit_(std::make_shared<FakeBistroWorker>(std::move(tso_cob))) { } cpp2::BistroWorker getBistroWorker() const; const std::string& shard() const { return shard_; } private: std::string shard_; CustomizeWorkerCob customizeWorkerCob_; apache::thrift::ScopedServerInterfaceThread ssit_; }; }}
29.631579
74
0.746892
bc8b87fc74e03851ee77bd196b290762e5e7fd01
162
h
C
eid.h
kchmck/mkbundle
8731b796f721cd2fec3026c2d3dd4a88e4c73784
[ "MIT" ]
1
2016-01-21T23:45:04.000Z
2016-01-21T23:45:04.000Z
eid.h
kchmck/mkbundle
8731b796f721cd2fec3026c2d3dd4a88e4c73784
[ "MIT" ]
null
null
null
eid.h
kchmck/mkbundle
8731b796f721cd2fec3026c2d3dd4a88e4c73784
[ "MIT" ]
null
null
null
// See copyright notice in Copying. #ifndef EID_H #define EID_H #include <inttypes.h> typedef struct { uint32_t scheme; uint32_t ssp; } eid_t; #endif
11.571429
35
0.697531
adc9c353ae6046652f1dd038fb613bd04c6a80cf
704
h
C
C++/C++ Advanced Nov 2019/12. Exam Preparation/exam21042019_Description/03. Memory Nightmare/Skeleton/MemoryContainer.h
galin-kostadinov/Software-Engineering
55189648d787b35f1e9cd24cc4449c6beda51c90
[ "MIT" ]
1
2019-07-21T13:00:31.000Z
2019-07-21T13:00:31.000Z
C++/C++ Advanced Nov 2019/12. Exam Preparation/exam21042019_Description/03. Memory Nightmare/Skeleton/MemoryContainer.h
galin-kostadinov/Software-Engineering
55189648d787b35f1e9cd24cc4449c6beda51c90
[ "MIT" ]
null
null
null
C++/C++ Advanced Nov 2019/12. Exam Preparation/exam21042019_Description/03. Memory Nightmare/Skeleton/MemoryContainer.h
galin-kostadinov/Software-Engineering
55189648d787b35f1e9cd24cc4449c6beda51c90
[ "MIT" ]
null
null
null
#ifndef MEMORYCONTAINER_H_ #define MEMORYCONTAINER_H_ #include "ContainerInterface.h" template <typename T> class MemoryContainer : public ContainerInterface { public: MemoryContainer() = delete; MemoryContainer(const size_t size) { _data = new T[size]; _dataCount = size; } virtual ~MemoryContainer() { delete[] _data; _data = nullptr; _dataCount = 0; } virtual size_t getOccupiedMemory() const override { return (sizeof(T) * _dataCount); } private: T * _data; size_t _dataCount; }; #endif /* MEMORYCONTAINER_H_ */
18.526316
57
0.558239
34607af6cbb073f2d629b79dbebff60eac9d1fa2
329
h
C
QtumJsIosServer/qtum-ios-develop/qtum wallet/Shared Views/Page Control/CustomPageControl.h
shekoocoder/telepathy
8da35e3dc41baf6f479b129dc723d8f321ccd39d
[ "MIT" ]
1
2019-07-08T09:33:56.000Z
2019-07-08T09:33:56.000Z
QtumJsIosServer/qtum-ios-develop/qtum wallet/Shared Views/Page Control/CustomPageControl.h
shekoocoder/telepathy
8da35e3dc41baf6f479b129dc723d8f321ccd39d
[ "MIT" ]
null
null
null
QtumJsIosServer/qtum-ios-develop/qtum wallet/Shared Views/Page Control/CustomPageControl.h
shekoocoder/telepathy
8da35e3dc41baf6f479b129dc723d8f321ccd39d
[ "MIT" ]
null
null
null
// // CustomPageControl.h // qtum wallet // // Created by Vladimir Lebedevich on 12.05.17. // Copyright © 2017 QTUM. All rights reserved. // #import <UIKit/UIKit.h> @interface CustomPageControl : UIPageControl @property (nonatomic, strong) UIImage *activeImage; @property (nonatomic, strong) UIImage *inactiveImage; @end
19.352941
53
0.729483
5531958c83ec0534219536946574f917ff70127c
1,233
h
C
FPBModule/Classes/Futool/UIFont+FUFont.h
pocozhang/FPBModule
da0ad77ecb3647f563a173255ea0d59f2142772b
[ "MIT" ]
null
null
null
FPBModule/Classes/Futool/UIFont+FUFont.h
pocozhang/FPBModule
da0ad77ecb3647f563a173255ea0d59f2142772b
[ "MIT" ]
null
null
null
FPBModule/Classes/Futool/UIFont+FUFont.h
pocozhang/FPBModule
da0ad77ecb3647f563a173255ea0d59f2142772b
[ "MIT" ]
null
null
null
// // UIFont+FUFont.h // FUSEPRO // // Created by tancheng on 2019/1/10. // Copyright © 2019 FUSENANO. All rights reserved. // /*** <string>Muli-ExtraLight.ttf</string> <string>Muli-ExtraLightItalic.ttf</string> <string>Muli-BoldItalic.ttf</string> <string>Muli-Black.ttf</string> <string>Muli-ExtraBold.ttf</string> <string>Muli-Bold.ttf</string> <string>Muli-ExtraBoldItalic.ttf</string> <string>Muli-Italic.ttf</string> <string>Muli-SemiBold.ttf</string> <string>Muli-SemiBoldItalic.ttf</string> <string>Muli-BlackItalic.ttf</string> <string>Muli-Light.ttf</string> <string>Muli-Regular.ttf</string> <string>Muli-LightItalic.ttf</string> */ #import <UIKit/UIKit.h> typedef enum : NSUInteger { FUFontTypeRegular, FUFontTypeSemiBold, FUFontTypeBold, FUFontTypeExtraBold, FUFontTypeExtraLight, FUFontTypeExtraLightItalic, FUFontTypeBoldItalic, FUFontTypeBlack, FUFontTypeExtraBoldItalic, FUFontTypeItalic, FUFontTypeSemiBoldItalic, FUFontTypeBlackItalic, FUFontTypeLight, FUFontTypeLightItalic, } FUFontType; NS_ASSUME_NONNULL_BEGIN @interface UIFont (FUFont) + (UIFont *)fontWithType:(FUFontType)fontType fontSize:(CGFloat)fontSize; @end NS_ASSUME_NONNULL_END
22.833333
73
0.751825
abb26ce2a9633aaaf50333995a2978c43079be63
797
h
C
RemoteTest/Constant.h
BboxLab/remote-template-ios
03f142834ff7d7e8df7566d5819ccc574accdadd
[ "MIT" ]
null
null
null
RemoteTest/Constant.h
BboxLab/remote-template-ios
03f142834ff7d7e8df7566d5819ccc574accdadd
[ "MIT" ]
null
null
null
RemoteTest/Constant.h
BboxLab/remote-template-ios
03f142834ff7d7e8df7566d5819ccc574accdadd
[ "MIT" ]
1
2021-06-11T18:36:12.000Z
2021-06-11T18:36:12.000Z
// // Constant.h // RemoteTest // // Created by Nicolas Jaouen on 29/01/2015. // Copyright (c) 2015 Bouygues Telecom. All rights reserved. // //Application and developper code #define Button_name @[ @"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0",@"UP",@"DOWN",@"LEFT",@"RIGHT",@"OK",@"BACK",@"EXIT"] //BBox api key #define BBoxIp @"bboxIp" #define BBoxControler @"BboxControler" #define Application_ApiKey @"Application" #define Media_ApiKey @"Media" // Key #define Body_KEY @"body" #define State_KEY @"state" #define AppName_KEY @"appName" #define PackageName_KEY @"packageName" #define MediaService_KEY @"mediaService" #define MediaState_KEY @"mediaState" #define MediaTitle_KEY @"mediaTitle" //Type #define Keypressed_Type @"keypressed" //Identifier #define Cell_Identifier @"Cell"
25.709677
126
0.697616
795043f6e135b0db3ebe0c131612ebdd365fd363
330
h
C
Framework/Graphics/Inc/OBJLoader.h
amyrhzhao/CooEngine
8d467cc53fd8fe3806d726cfe4d7482ad0aca06a
[ "MIT" ]
3
2020-07-23T02:50:11.000Z
2020-10-20T14:49:40.000Z
Framework/Graphics/Inc/OBJLoader.h
amyrhzhao/CooEngine
8d467cc53fd8fe3806d726cfe4d7482ad0aca06a
[ "MIT" ]
null
null
null
Framework/Graphics/Inc/OBJLoader.h
amyrhzhao/CooEngine
8d467cc53fd8fe3806d726cfe4d7482ad0aca06a
[ "MIT" ]
null
null
null
#ifndef INCLUDED_COOENGINE_GRAPHICS_OBJLOADER_H #define INCLUDED_COOENGINE_GRAPHICS_OBJLOADER_H #include "Mesh.h" namespace Coo::Graphics { class ObjLoader { public: static void Load(const std::filesystem::path& filePath, float scale, Mesh& mesh); }; } #endif // !INCLUDED_COOENGINE_GRAPHICS_OBJLOADER_H
20.625
84
0.751515
5ebca9f23eb7e52c6a772047f9460e541e17732e
615
h
C
gob/CmpFileData.h
mattbierner/gober
dddcecd72a8dc447054808b3026893ac3a0f3d95
[ "MIT" ]
3
2015-06-01T19:09:45.000Z
2017-04-16T14:17:03.000Z
gob/CmpFileData.h
mattbierner/libgob
dddcecd72a8dc447054808b3026893ac3a0f3d95
[ "MIT" ]
null
null
null
gob/CmpFileData.h
mattbierner/libgob
dddcecd72a8dc447054808b3026893ac3a0f3d95
[ "MIT" ]
null
null
null
/** Structures for reading a CMP (color light level mapping) from binary data. */ #pragma once #include <stdint.h> #include <gob/Common.h> namespace Df { /** Mapping for one light level in the colormap. */ PACKED(struct CmpFileColorMap { /** Indicies into a PAL file. */ uint8_t colors[256]; }); /** Complete CMP file. */ PACKED(struct CmpFileData { /** Collection of color mappings for the 32 different light levels. */ CmpFileColorMap colorMaps[32]; /** Additional shading used for the headlight and weapon lighting effects. */ uint8_t headlightMap[128]; }); } // Df
18.088235
81
0.669919
f91397475df9f1a7a8c006fe0bf7b0162104e2b8
2,309
h
C
include/arch/arm/cortex_m/memory_map.h
13824125580/zephyr-rr
531cd1b8d0663172dc6b4dd7cdfe91c26304706c
[ "Apache-2.0" ]
9
2016-10-07T15:31:17.000Z
2019-02-21T05:32:59.000Z
include/arch/arm/cortex_m/memory_map.h
13824125580/zephyr-rr
531cd1b8d0663172dc6b4dd7cdfe91c26304706c
[ "Apache-2.0" ]
2
2016-08-30T01:28:57.000Z
2017-09-27T01:50:28.000Z
include/arch/arm/cortex_m/memory_map.h
13824125580/zephyr-rr
531cd1b8d0663172dc6b4dd7cdfe91c26304706c
[ "Apache-2.0" ]
5
2016-06-11T07:44:20.000Z
2021-06-12T17:41:37.000Z
/* * Copyright (c) 2014 Wind River Systems, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file * @brief ARM CORTEX-M memory map * * This module contains definitions for the memory map of the CORTEX-M series of * processors. */ #ifndef _CORTEXM_MEMORY_MAP__H_ #define _CORTEXM_MEMORY_MAP__H_ #include <misc/util.h> /* 0x00000000 -> 0x1fffffff: Code in ROM [0.5 GB] */ #define _CODE_BASE_ADDR 0 #define _CODE_END_ADDR (_CODE_BASE_ADDR + MB(512) - 1) /* 0x20000000 -> 0x3fffffff: SRAM [0.5GB] */ #define _SRAM_BASE_ADDR (_CODE_END_ADDR + 1) #define _SRAM_BIT_BAND_REGION (_SRAM_BASE_ADDR) #define _SRAM_BIT_BAND_REGION_END (_SRAM_BIT_BAND_REGION + MB(1) - 1) #define _SRAM_BIT_BAND_ALIAS (_SRAM_BIT_BAND_REGION + MB(32)) #define _SRAM_BIT_BAND_ALIAS_END (_SRAM_BIT_BAND_ALIAS + MB(32) - 1) #define _SRAM_END_ADDR (_SRAM_BASE_ADDR + MB(512) - 1) /* 0x40000000 -> 0x5fffffff: Peripherals [0.5GB] */ #define _PERI_BASE_ADDR (_SRAM_END_ADDR + 1) #define _PERI_BIT_BAND_REGION (_PERI_BASE_ADDR) #define _PERI_BIT_BAND_REGION_END (_PERI_BIT_BAND_REGION + MB(1) - 1) #define _PERI_BIT_BAND_ALIAS (_PERI_BIT_BAND_REGION + MB(32)) #define _PERI_BIT_BAND_ALIAS_END (_PERI_BIT_BAND_ALIAS + MB(32) - 1) #define _PERI_END_ADDR (_PERI_BASE_ADDR + MB(512) - 1) /* 0x60000000 -> 0x9fffffff: external RAM [1GB] */ #define _ERAM_BASE_ADDR (_PERI_END_ADDR + 1) #define _ERAM_END_ADDR (_ERAM_BASE_ADDR + GB(1) - 1) /* 0xa0000000 -> 0xdfffffff: external devices [1GB] */ #define _EDEV_BASE_ADDR (_ERAM_END_ADDR + 1) #define _EDEV_END_ADDR (_EDEV_BASE_ADDR + GB(1) - 1) /* 0xe0000000 -> 0xffffffff: varies by processor (see below) */ #if defined(CONFIG_CPU_CORTEX_M3_M4) #include <arch/arm/cortex_m/memory_map-m3-m4.h> #else #error Unknown CPU #endif #endif /* _CORTEXM_MEMORY_MAP__H_ */
34.462687
80
0.750974
bf025399d9392ed7910d34c8c0b7309c125f92e9
82
h
C
kernels/linux-2.6.24/include/asm-x86/hw_irq.h
liuhaozzu/linux
bdf9758cd23e34b5f53e8e6339d9b29348615e14
[ "Apache-2.0" ]
null
null
null
kernels/linux-2.6.24/include/asm-x86/hw_irq.h
liuhaozzu/linux
bdf9758cd23e34b5f53e8e6339d9b29348615e14
[ "Apache-2.0" ]
1
2021-04-09T09:24:44.000Z
2021-04-09T09:24:44.000Z
include/asm-x86/hw_irq.h
KylinskyChen/linuxCore_2.6.24
11e90b14386491cc80477d4015e0c8f673f6d020
[ "MIT" ]
1
2020-03-08T00:59:27.000Z
2020-03-08T00:59:27.000Z
#ifdef CONFIG_X86_32 # include "hw_irq_32.h" #else # include "hw_irq_64.h" #endif
13.666667
23
0.743902